How to set variable in twig using Drupal 8?

Member

by lottie , in category: PHP Frameworks , a year ago

How to set variable in twig using Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 9 months ago

@lottie 

In Drupal 8, you can set a variable in a Twig template using the set function. Here's an example:

1
{% set myVariable = "some value" %}


You can then use the myVariable variable in the template like this:

1
{{ myVariable }}


You can also set variables in Twig templates using context passed from the theme or module. For example, if you want to set a variable in a Twig template that is being rendered by a module, you can pass the variable in the render array like this:

1
$build['my_variable'] = [  '#type' => 'markup',  '#markup' => 'some value',];


Then in your Twig template, you can access the variable like this:

1
{% set myVariable = my_variable['#markup'] %}


I hope this helps! Let me know if you have any questions.