I have a module in Drupal 8 to build a configuration form where I can set the value of a variable. But I don't know how to retrieve the value of that variable from the twig template.

In Drupal 7 I just needed variable_get() to get the value. What is the equivalent code that I should use in Drupal 8?


The values saved as configuration items can be accessed using code similar to the following one.

$slogan = \Drupal::config('system.site')->get('slogan');

Since you are asking for a template file, that code should be split in two parts. My example is for the node.html.twig template file, but you can use the same kind of code for other template files too.

  • In the preprocess function of your template file (e.g. mytheme_preprocess_node(&$variables)) you get the value of the configuration item

    $variables['slogan'] = \Drupal::config('system.site')->get('slogan');
  • In the template file (e.g. node.html.twig), you access that variable

    {{ slogan }}

Be sure not to use a variable ($variables['slogan'], in my example) that is not already used from the template file, or its preprocess functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.