Stevan Tosic Stevan Tosic - 2 months ago 21
Twig Question

Twig block USE in IF block

I render same page in modal and self.

I wonder if there is some way to check for some condition and if condition is true not to include header and footer with use tag.

{% extends 'ProfileBundle::base.html.twig' %}

{% block stylesheets %}
{{ parent() }}
<link href="..."/>
{% endblock %}

{% if modal is not defined %}
{% use 'ProfileBundle::navigation.html.twig' %}
{% use 'ProfileBundle::footer.html.twig' %}
{% endif %}

{% block main %}
{% endblock %}

Answer

To use the use tag in twig, you still need to call them if you want to render the blocks. So before rendering the blocks you can add your condition (twigfiddle)

page.twig

{% extends "base.twig" %}

{% block stylesheets %}
    {{ parent() }}
    <link rel="text/css" href="page.css" />
{% endblock %}

{% block content %}
    {% if not modal is defined %}{{ block('navigation') }}{% endif %}

    <h1>Content</h1>

    {% if not modal is defined %}{{ block('footer') }}{% endif %}
{% endblock %}  

base.twig

{% use "navigation.twig" %}
{% use "footer.twig" %}

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="UTF-8">
        {% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="default.css" />
        {% endblock %}
    </head>
    <body>      
        {% block content %}
        {% endblock %}
    </body>
</html>

navigation.twig

{% block navigation %}
<nav id="main">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
</nav>
{% endblock %}

footer.twig

{% block footer %}
<footer>
    &copy; {{ "now" | date('Y') }}
</footer>
{% endblock %}
Comments