How to set variable in twig using Drupal 8?

Member

by lottie , in category: PHP Frameworks , 3 years ago

How to set variable in twig using Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by filiberto , 2 years 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.

by muriel.schmidt , a year ago

@lottie 

Just to clarify, it looks like you may have a small error in the last line of code. It should be:


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


Thank you for understanding. Let me know if you need any further assistance.

Related Threads:

How to render block in twig using Drupal 8?
How to get url in Drupal 8?
How to remove numbers using twig in octobercms?
How to load node by id in Drupal 8?
How to print query in Drupal 8?
How to upload file in Drupal 8?