Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to twig using hook_theme within a module

I'm fully aware how to do this in Drupal 7 so I will explain what I would normally do using Drupal 7.

When making a custom module I use hook_theme a lot, it is very powerful and reusable!

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
    $themes = array();

    $themes['name_of_theme'] = array(
      'path' => drupal_get_path('module', 'module') .'/templates',
      'template' => 'NAME_OF_TEPLATE',
      'variables' => array(
        'param1' => NULL,
        'param2' => NULL,
      ),
    );

    return $themes;
}

I would then call this theme using

theme('name_of_theme', array(
   'param1' => 'VALUEA',
   'param2' => 'VALUEB'
)); 

This would then return html and I would be happy.

So Drupal 8 is out need to get to grips with it.

/**
 * Implements hook_theme().
 */
function helloworld_theme() {
  $theme = [];

  $theme['helloworld'] = [
    'variables' => [
      'param_1' => [],
      'param_2' => 'hello',
    ]
  ];

  return $theme;
}

and within my controller I'm am using

$hello_world_template = array(
  '#theme' => 'helloworld',
  'variables' => [
    'param_1' => 'hello world',
    'param_2' => 'hello from another world'
  ],
);

$output = drupal_render($hello_world_template,
  array(
    'variables' => array(
      'param_1' => $param_1,
      'param_2' => $param_2,
    )
  )
);

return [
    '#type' => 'markup',
    '#markup' => $output
];

I am getting an output on of my template, however what Im not sure about is where to pass my parameters so that they are available in my template (just to point out that my variables are available they are just null as defined in hook_theme)

I'm also open to the idea that I might be doing the fundamentally wrong and I'm open to an alternative route if my method is not best practise.

like image 542
Jake Lacey Avatar asked Dec 05 '15 19:12

Jake Lacey


1 Answers

Found the issue,

changing this,

$hello_world_template = array(
  '#theme' => 'helloworld',
  'variables' => [
    'param_1' => 'hello world',
    'param_2' => 'hello from another world'
  ],
);

to this,

$hello_world_template = array(
  '#theme' => 'helloworld',
  '#param_1' => $param_1,
  '#param_2' => $param_2
);

Im now able see the variables I'm passing.

I am still open for a better option?

like image 58
Jake Lacey Avatar answered Oct 16 '22 17:10

Jake Lacey