Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Twig Custom Set Variables From an Include

Tags:

twig

symfony

I'm trying to include a twig file with a bunch of custom set variables and then use the variables in the multiple other template files. Similar to how including a PHP file works.

I don't seem to have access to the variables set inside the include in my index file.

Is there any way to do this?

Sample Code *Edited

Included File:

{# variables.html #}
{% set width = "100" %}
{% set height = "250" %}

Template File:

{# index.html #} 
{% include 'variables.html' %}
{{ width }}
{{ height }}

Expected Outcome:

100 250

Actual Outcome:

// Nothing gets output
like image 453
King724 Avatar asked Dec 05 '13 20:12

King724


People also ask

How do I pass variables to Twig Drupal 8?

to print variable in twig file just use {{ my_variable }}.

What is raw in Twig?

raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter. This only works if the raw filter is the last filter that is applied to the filter.


1 Answers

As far as I know it is only possible with {% extends %} tag. Instead of including template with variables you should extend it.

Example:

variables.tpl:

{% set some_variable='123' %}
... more variables ...

{% block content %}
{% endblock %}

template.tpl

{% extends 'variables.tpl' %}

{% block content %}
{{ some_variable }}
... more code which uses variables assigned in variables.tpl ...
{% endblock %}
like image 124
jmarceli Avatar answered Oct 01 '22 02:10

jmarceli