Twig: Dynamic block names

Created on 12 Apr 2011  ·  7Comments  ·  Source: twigphp/Twig

Using vars for block names not working.

{% set block_name = "my_block_name" %}

{% block block_name %}
some html ...
{% endblock %}

Most helpful comment

Block names are part of the structure of the template, and so must be known at compile time.
Variables are only known at runtime.

All 7 comments

because block_name represented as string 'block_name'

Sorry, you are saying that you can't have dynamic blocks with twig or that I'm using it in the wrong way ?

You are right, no dynamic block names

You cannot use dynamic blocks. Post your use case on the Twig user mailing-list.

Sorry for opening a cold case ^^. I think I may have encountered a use case that would benefit from the dynamic block names...

I use Doctrine with single table inheritance (base abstract class = Article, and News + Faq extends Article).

Then, I have created form classes to be able to create News and Faq. But all forms use the same twig template. Then I needed to customize a field template (say article.product) as described here.

The problem is that, the name of the field changes depending on which form is used. The name will be either news_product or faq_product, so it would be handy to be able to customize my form fields like this to avoid repetitions:

{%- block '_'~type~'_product_widget' -%} ... {% endblock %}

After some research, I solved this by forcing the prefix of the form in the different form type classes using getBlockPrefix, so that all forms will have the same field names, and I can simply customize article_product:

public function getBlockPrefix(){ return 'article'; }

So just wanted to document this use case which may help someone...

Block names are part of the structure of the template, and so must be known at compile time.
Variables are only known at runtime.

Was this page helpful?
0 / 5 - 0 ratings