samanime
samanime

Reputation: 26615

Symfony2 Twig Inject additional blocks

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

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

Any ideas?


Clarification

Say I have a generic block which can do something, like:

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

I have a class which knows it wants to be rendered with this block. My template itself doesn't necessarily know this though.

 {{ block(myObj.blockName) }}

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

Similar to registering custom Twig functions with a TwigExtension. My template doesn't need to explicitly know it's there, it just has to be available at run-time.

Does that make sense?


To clarify a bit further, I'm essentially looking to do something just like how there are default Twig blocks for rendering Forms in Symfony2. I don't have to include the default form file every time, just when I want to change something.

Upvotes: 3

Views: 2165

Answers (2)

samanime
samanime

Reputation: 26615

I went digging around in the Symfony source code to try and find my answer. It looks like there isn't some fancy, neat way to embed it from a configuration file or controller directly, which is a bit disappointing, but not a huge deal.

So, to solve my situation, I'll be using the "use" keyword to include my block file in my base template, so it will then be available to 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 sufficiently close.

Upvotes: 2

DarkLeafyGreen
DarkLeafyGreen

Reputation: 70466

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

Thats what I say. 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 returns only string value. http://twig.sensiolabs.org/doc/advanced.html#id2

Upvotes: 0

Related Questions