Conditionally define a block in twig 2

therefore heres is used:

  • display the login form block in the dynamic structure of the page, but only if the user has not authenticated
  • should not be determined if not authenticated (to preserve the dynamic structure of the page)

twig 2.2
symfony 3.2


In the base template, I only execute the block if it is defined (not "not emtpy")

base.html.twig

{% if block('left_sidebar') is defined %}
      <div class="col-md-2">
           {{- block('left_sidebar') -}}
      </div>
      <div class="col-md-10">
{% else %}
      <div class="col-md-12">
{% endif %}

index.html.twig

In order for the above work to be done, the can not block is defined at all (which is fully developed). In any case, the block makes the block anyway, and I cannot understand why.

{% if not is_granted('IS_FULLY_AUTHENTICATED') %}
    {% block left_sidebar %}
        {% include ':blocks:block__login.html.twig' %}
    {% endblock %}
{% endif %}

, is'nt , . , .

- , ? , ?

true, false, .

+4
3

, , , , , , , /.

, if .

heres github, - .

0

Twig php, symfony cache, - . , , , , , .

is_granted . - if index.html.twig, , .

, . , , , , symfony.

0

The function block()seems to return false if there was nothing in it or just empty space, so you can wrap the block in a validation test and make sure that it is empty in the child template if you do not want it to show. Something like this worked for me:

base.html.twig:

{% if block('left_sidebar') %}
        <div class="col-md-2">
            {% block left_sidebar %}{% endblock %}
        </div>
        <div class="col-md-10">
{% else %}
        <div class="col-md-12">
{% endif %}

index.html.twig

{% block left_sidebar %}
    {% if not is_granted('IS_FULLY_AUTHENTICATED') %}
        {% include ':blocks:block__login.html.twig' %}
    {% endif %}
{% endblock %}
0
source

Source: https://habr.com/ru/post/1669503/


All Articles