Score:0

All variables invisible to twig files

do flag

I created a theme whose minimal.theme file contains the following lines (among others).

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function minimal_preprocess_node(&$variables) {
  // Declare the test variable and set its value.
  $variables['test_variable'] = 'Hello, this is a test variable!';
}

The following is the content of the template file.

{#
  This is a custom Twig template for the front page (homepage).
  It will override the default page template for the front page.
#}
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Head content here -->
</head>
<body>
  <header>
    <h1>Welcome to Our Website</h1>
  </header>

  <main>
    <div class="my-custom-class">
      <p>{{ test_variable }}</p> {# not showing up #}
    </div>
  </main>
</body>
</html>

The template file does not show the value for test_variable?

What else do I need to do to make test_variable usable in the template file?

leymannx avatar
ne flag
Preprocess node hook will make variables available in node templates. You are in the page template. Use preprocess page hook.
Score:4
us flag

Variables that are set in hook_preprocess_node() are only accessible in node templates. You are trying to access test_variable in a page template and that is the reason why that template file does not render any value for test_variable.

If you want to add the same variable to all the template files, you should implement hook_preprocess().

/**
 * Implements hook_preprocess().
 */
function minimal_preprocess(&$variables, $hook, $info) {
  // Declare the test variable and set its value.
  $variables['test_variable'] = 'Hello, this is a test variable!';
}

You could also implement hook_preprocess() when the same code is used for more than one template file, but not all the template files. In that case, you can check the value of $hook.

/**
 * Implements hook_preprocess().
 */
function minimal_preprocess(&$variables, $hook, $info) {
  if ($hook == 'page' || $hook == 'node') {
    // The variable is accessible only from page and node templates.
    $variables['test_variable'] = 'Hello, this is a test variable!';
  }
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.