Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a block exists in a twig template - Symfony2

Tags:

twig

symfony

Imagine I have something like this in my twig template

{% block posLeft %}    ----- {%endblock%} 

Is there any way to check for existance of the posLeft block without calling to:

block("posLeft")  

And check the return value of the posBlock to varify the existance. I am a newbie in Symfony2 + Twig.

like image 348
channa ly Avatar asked Dec 08 '12 04:12

channa ly


People also ask

What is block in Twig?

Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag. Block names must consist of alphanumeric characters, and underscores. The first char can't be a digit and dashes are not permitted.

How do you check if a Twig is empty?

should check whether the variable is null or empty. If you want to see if it's not null or empty just use the not operator. See the docs: empty.

How do you find the current route in Twig?

You can get the current URL in Twig/Silex 2 like this: global. request. attributes. get('_route') .


1 Answers

You can solve it like this, if you want to display a certain block only if it has content. Hope, this is what you're looking for.

Example index.html.twig

{% set _block = block('dynamic') %} {% if _block is not empty %}     {{ _block|raw }} {% endif %} 

Example part.html.twig

{% extends "index.html.twig" %}  {% block dynamic %}     Block content goes here. {% endblock %} 
like image 182
insertusernamehere Avatar answered Sep 23 '22 12:09

insertusernamehere