Reputation: 490
I have an odd situation where my twig template builds content to fit into several "boxes" such that the number of containing boxes can vary in number. I'm looking for a general way of defining n blocks in the child template and the parent will render the right number. Here is an example of what my child template looks like now:
{% extends "layout.participant.html.twig" %}
{% block box_left_title %}Personal Information{% endblock %}
{% block box_left_content %}
content here
{% endblock %}
Consider that there could be one, two or potentially 5 of these paired title/content sections. What I'm imagining is some sort of way to define box_left_title
as the first array slot and then the parent template (layout.participant.html.twig
) would iterate each block and build as many "boxes" as necessary.
The workaround I'm considering right now is to define blocks of box_left_content_1
, box_left_content_2
, and so on in the parent template and then define only the ones used in the child. While it will work it feels wrong.
Am I mis-using template inheritance here? Should I instead look into conditional includes? Pointers on this are most welcome.
Update: My question presumed that I could have dynamic blocks in the parent template, but this turns out to not be possible. I believe I'm going to need to define block1
, block2
etc in the parent (allowing for a reasonable upper limit) and then provide blocks with content in the children. This is all assuming that includes aren't the preferred approach.
Upvotes: 2
Views: 868
Reputation: 709
You have multiple approaches. The easiest though would probably be inclusion.
http://twig.sensiolabs.org/doc/templates.html#including-other-templates
Say boxes is an array that looks like this: $boxes = array( array( 'title' => 'First Title', 'content' => 'the content of one', ), array( 'title' => 'Second Title', 'content' => 'the content of two', ), );
You would use this in twig:
{% for box in boxes %}
{% include "render_box.html" %}
{% endfor %}
Now the render_box.html would run inside this for loop context, so the box vairable is present in this template. Your render_box.html would look like this:
<h1>{{ box.title }}</h1>
<p>{{ box.content }}</p>
Upvotes: 2