Dean Gibson Dean Gibson - 6 months ago 10
PHP Question

Twig, pass in block (e.g. h1) in includes

If I'm including a template like this:

{% include 'mytemplate.twig' %}


Can I pass a block in like this for example:

{% include 'mytemplate.twig'
<h1>Hello World</h1>
%}


And have it rendered inside my other template.. Something like this:

// mytemplate.twig

<div>
{{ content }}
</div>

Answer

You have 2 options:

  1. Pass the content as a variable :

    {% include 'mytemplate.twig' with {'content': 'Title', } %}

do note you will need to modify the template to : {{ content | raw }} in order to parse the HTML

  1. Define a block inside the template :
{% block content %}{% endblock %}


And then use embed instead :

{% embed "mytemplate.twig" %}
{% block content %}
   <h1>Title</h1>
{% endblock %}
{% endembed %}