4

I have a module that sets the value of a configuration object. I don't know how to retrieve that value from a template file.

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

1

1 Answer 1

14

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 already used from the template file, or its preprocess functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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