Skip to content

Instantly share code, notes, and snippets.

@schnippy
Last active May 18, 2021 21:30
Show Gist options
  • Save schnippy/069f662464a1c1fc7341d052b634b3e1 to your computer and use it in GitHub Desktop.
Save schnippy/069f662464a1c1fc7341d052b634b3e1 to your computer and use it in GitHub Desktop.

HOWTO: Expose a value in twig templates

We want to encourage front-end developers to use twig templates whenever possible as it makes long-term maintenance and update of the site a lot simpler for everyone involved if the code is easy to read like this:

<h1> Hello, {{ user.first_name }} {{ user.last_name }} </h1>

<p> Today's weather forecast is {{ forecast }} </p>

However in the above simplified example, you can probably see that one of these is going to be readily available by default in Drupal (ex. show me the value of the first_name field from the logged in user) while the other may need to be handled in a custom module. For this example, we might be pulling the forecast from a separate site using a Guzzle REST call, parsing the result and returning it as a formatted result, not something we want to build out in Twig.

For this, all we need to do is use a preprocess function to define our variable. This can occur at several levels (ex. _preprocess_page, _preprocess_node, etc.) wherever it makes sense for your use case.

In this example, we are going to display the above {{ forecast }} message on every page so we can use a _preprocess_page hook in our module (or theme)

https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_page/8.2.x

Here, all we need to do is pass the $variables array by reference and add our value to it.

function mymodule_preprocess_page(&$variables) {
  $variables["forecast"] = my_complex_forecast_generating_routine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment