O
O
Outsider V.2017-07-15 13:30:16
Twig
Outsider V., 2017-07-15 13:30:16

How to get variables from included Twig template?

The templates of different pages use the same array of output fields, I decided to move the definition of this array to a separate file:
base_fields.twig

{% set base_fields = ["id", "name", "description", "priority"] %}

index.html.twig
{% extends '@App/Default/layout.html.twig' %}
{% block base_fields %}
    {% include '@App/task_abstract/base_fields.twig' with vars %}
{% endblock %}

(inclusion outside of blocks for templates that extend others is forbidden)
But as a result I get "Variable "base_fields" does not exist."
Why doesn't it work, and how do I implement what I want?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
justpusher, 2017-07-20
@justpusher

It's just that different templates have a different context, the variables are not global.
I see two options:
1. Make a common parent template for templates using base_fields and declare base_fields in the parent.
2. Write an extension for twig with functions like setMyVar and getMyVar (although this is ugly).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question