J
J
John Doe2018-10-01 18:06:34
Twig
John Doe, 2018-10-01 18:06:34

How to use a template in Twig depending on the situation?

There are several Twig templates, and the page where you want to display them depending on the value of the variable. But for some reason Twig ignores the conditions and uses the last included template, in this example "template2.twig".

{% extends 'layout.twig' %}

{% if foo == bar %}
    {% use 'template1.twig' %}
{% else %}
    {% use 'template2.twig' %}
{% endif %}

{% block content %}{% endblock %}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
John Doe, 2018-10-04
@rabbit418

It turned out to solve the problem with a simple investment.
There is a layout.twig file with the base template in it, then an index.twig file with the page template in it, and separate files for each of the microtemplates.
layout.twig :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

index.twig :
{% extends 'layout.twig' %}

{% block content %}
    {% block info %}{% endblock %}
{% endblock %}

Well, template1.twig for example:
{% extends 'index.twig' %}

{% block info %}Hello World{% endblock %}

Well, on the page we render template1.twig.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question