Symfony2 Twig Inject additional blocks

Is there a way with Symfony2 and Twig to always make available files that only contain blocks.

For example, if I wanted to make a block named "cookie" always available in any template on my system, without having to always include or extend it in the template I use.

Any ideas?


Lightening

Let's say I have a generic block that can do something, like:

{% block myBlock %}
    ABC Examples
{% endblock %}

      

I have a class that knows that it wants to be represented by this block. My template itself doesn't necessarily know this.

 {{ block(myObj.blockName) }}

      

I would like this to be my controller / services / etc. can register a file that contains this block, without my template really needing to know about it directly (so I could have multiple files like this, each working with some common interface).

This is similar to registering custom Twig functions with TwigExtension. My template doesn't have to explicitly know it there, it just needs to be available at runtime.

It makes sense?


To clarify a little further, I essentially want to do something like the default Twig blocks for rendering forms in Symfony2. I don't have to include a standard form file every time, only when I want to change something.

+3


source to share


2 answers


I went digging through the Symfony source code to try and find my answer. There doesn't seem to be any fancy, neat way to inline it from a config file or controller directly, which is a bit frustrating but not a huge deal.

So, to solve my situation, I will use the "use" keyword to include my block file in the base template, so it will be available for everything else.



{# widget_blocks.html.twig #}
{# Widgets #}
{% block my_widget %}
    ABC Cookies
{% endblock %}

{# base.html.twig #}
{% use widget_blocks.html.twig %}
{{ block(my_widget.block) }}

      

Not exactly what I wanted, but close enough.

+2


source


{% render 'MyMainBundle:Default:credits' with {'arg1': $myObj } %}

      

Here's what I'm talking about. What's the difference between the line above or



{{ block(myObj.blockName) }}

      

You can register a custom filter, but as far as I know it only returns a string value. http://twig.sensiolabs.org/doc/advanced.html#id2

0


source







All Articles