Drupal - How do I pass a theme variable from a template to another?

The solution I am working with is to use drupal_static(); simplified essentials in code below - take care with the &ampersands. It is giving me control where I need it.

So, using this approach, I can - taking their global context into account - per field, set variables in the usual way e.g. in mytheme_preprocess_field() subsequently to be used in a related template like field--node--title--agenda.html.twig

function mytheme_preprocess_simplenews_newsletter_body(&$variables) {
  // prepare to alter static var ...
  // get a reference binding to static var
  $var = &myvariable_function();
  // alter static var
  $var = 'simplenews_newsletter';
}

function mytheme_preprocess_field(&$variables, $hook) {
  // prepare to read static var
  // assign static var
  $var = myvariable_function();
  // $element is the render array for the field
  $element = $variables['element'];
  // filter those cases where it matters that we're theming a newsletter
  if ($element['#view_mode'] == 'email_html' and $var == 'simplenews_newsletter') {
    // Do stuff here like setting a variable for twig ...
    $variables['summons'] = 'some text';
  }
}
function &myvariable_function() {
  $var = &drupal_static(__FUNCTION__);
  if (!isset($var)) {
    // generate contents of static variable
    $var =  'initial_value';
  }
  return $var;
}

I am sure that there are other ways of communicating common context between different levels of a page's render hierarchy. Let me know how you'd do it.

Tags:

Theming

8

Hooks