King724
King724

Reputation: 171

Use Twig Custom Set Variables From an Include

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

Upvotes: 16

Views: 24887

Answers (3)

You can use a template extension : https://symfony.com/doc/current/templating/twig_extension.html

post|entry_date

Upvotes: -1

jmarceli
jmarceli

Reputation: 20152

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 %}

Upvotes: 4

imjared
imjared

Reputation: 20554

I was just trying to do the same thing you were and came up with the following:

Created snippets.twig to maintain all these mini variables. In your case, you might call it variables.twig. In this file, I used a macro without any arguments. I was creating formatted entry date markup that I can use across all my templates and it looked like this:

{% macro entry_date() %}
<time datetime="{{post.post_date|date('m-d-Y')}}">{{post.post_date|date('F j, Y')}}</time>
{% endmacro %}

note that the parenthesis after the name declaration were imperative

In my main layout file, layout.twig, I referenced this macro via an import statement so it would be accessible in all child templates:

{% import "snippets.twig" as snippets %}
<!doctype html>
...

In my template files, I now have snippets accessible and can query it like any other variable:

{{ snippets.entry_date }}

UPDATE

This doesn't seem to correctly run code. If you're just storing static content, you should be good. You can also pass args to the macro so I imagine you could make some magic happen there but I haven't tried it.

Upvotes: 5

Related Questions