<p>AFAIK it's not possible to have Twig execute arbitrary code from a string like that – there is the <a href="https://twig.symfony.com/doc/3.x/functions/template_from_string.html" rel="nofollow noreferrer"><code>template_from_string()</code></a> function, but that will only render output, similarly to a macro or include, i.e. not return anything like you need the <code>.all()</code> to do.</p>
<p>However, considering the <code>item</code> variable is redundant outside the loop in the <code>_partnerList.twig</code> template (it's defined inside that template, after all) and the <code>.all()</code> is also redundant outside (as you can easily call it inside the partner list loop), you can omit both of those parts. At that point, you're left with the <code>'projectsPartnered'</code> field handle – which <em>can</em> be passed as a string variable and used inside the <code>_partnerList.twig</code> template like this:</p>
<p>The include:</p>
<pre><code>{% include '_partials/_partnerList.twig' with {
    items: craft.entries.section('partners').orderBy('title').all(),
    linkage: 'projectsPartnered'
} %}
</code></pre>
<p>In the <code>_partnerList.twig</code> template:</p>
<pre><code>{% for item in items %}
    {{ item.title }}

    {% if linkage is defined %}
        {% for project in item[linkage].all() ?? [] %}
            {{ project.title }}
        {% endfor %}
    {% endif %}
{% endfor %}
</code></pre>
<p>The key here being the <code>item[linkage].all()</code> part.</p>
<p>Note that I added a couple of defensive measures to the code. First, the <code>{% if linkage is defined %}</code> conditional is to make sure you don't run into an error if the <code>_partnerList.twig</code> template is ever included <em>without</em> supplying a <code>linkage</code> variable. Second, the null coalescing operator (<code>??</code>) after the call to <code>.all()</code> is to make sure the statement defaults to an empty array, instead of throwing an exception, in cases where the <code>linkage</code> variable might refer to a field that doesn't actually exist in the <code>item</code> element's field layout.</p>

CC BY-SA 4.0
2024-10-02T22:27:32.640Z
— this answer is absolutely spot one.
dezbat
CC BY-SA 4.0
2024-10-02T22:35:58.607Z
— Beautifully explained too. I do find it frustrating not always understanding how / why certain things operate in Twig (in this case the square bracket syntax), I guess learning by example as here is the best way :)

But would love to know if you recommend any decent Twig / templating education or indeed if you have anything out there.

many thanks

Matt
dezbat
CC BY-SA 4.0
2024-10-02T23:40:10.580Z
@dezbat I'm happy it was helpful ❤️ I think Twig generally strikes a pretty perfect balance between "real" PHP and a very simplified template language, but the fact that something like `.item[foobar]` works (where `foobar` is a variable referring to an object method or property – in this case a custom field on an entry) is definitely something that comes from the PHP side of things, and it's not something Twig makes apparent. I'd give you some links if I could, but generally I'd advice digging into PHP basics, as once you get an understanding of PHP, Twig kind of opens up a lot.
Mats Mikkel Rummelhoff
CC BY-SA 4.0
2024-10-02T23:58:57.143Z
Also, James' answer isn't wrong and in many cases the `{% embed %}` tag (which is admittedly one of the harder Twig tags to wrap one's head around) might be a more robust way to approach problems like this!
Mats Mikkel Rummelhoff
CC BY-SA 4.0
2024-10-01T20:08:11.870Z
2024-10-02T23:29:15.113Z
2024-10-02T23:29:15.113Z
Mats Mikkel Rummelhoff
<p>What you're trying to do is possible using &quot;variable variables&quot; (i.e., a Twig object with a dynamically named sub-property), however in my opinion a better approach would be to use <code>embed</code> which is ideally suited for this purpose. <a href="https://twig.symfony.com/doc/3.x/tags/embed.html" rel="nofollow noreferrer">https://twig.symfony.com/doc/3.x/tags/embed.html</a></p>
<h2>Variable variables</h2>
<p>If you want to persist with the &quot;variable variables&quot; approach, it looks like the later versions of Twig (3.15+) now support this via the <a href="https://twig.symfony.com/doc/3.x/templates.html#dot_operator" rel="nofollow noreferrer">dot operator</a> - you can pass an expression like this: <code>{% for project in item.(linkage).all() %}</code> - then you'd pass in a string for the <code>linkage</code> variable telling the partial which named property to use, i.e. <code>linkage: 'projectsPartnered'</code>. Earlier versions of Twig need to use the <code>attribute()</code> function for variable variables. <a href="https://twig.symfony.com/doc/3.x/functions/attribute.html" rel="nofollow noreferrer">https://twig.symfony.com/doc/3.x/functions/attribute.html</a> Though I've often found you can also do it with square bracket syntax instead of dot notation, i.e. <code>item[linkage].all()</code>. I haven't tested all those, because the better solution to your problem is...</p>
<h2>Embed</h2>
<p>Embeds are better for this in my opinion as they allow for full flexibility via block overrides. You could use the <code>{{ parent() }}</code> function to delegate responsibility for outputting the actual markup to the embed, so you're basically just setting variables to be consumed by the embed - it can work in lots of different ways, but try something like this (I've also added <a href="https://craftcms.com/docs/5.x/development/eager-loading.html" rel="nofollow noreferrer">eager loading</a> for the first embed):</p>
<pre class="lang-twig prettyprint-override"><code>{# ==================================
index.twig
===================================== #}

{% embed '_partials/_partnerList.twig' with {
    items: craft.entries.section('partners').with(['projectsPartnered']).orderBy('title').all()
}%}
    {% block subItemsBlock %}
        {% set subItems = item.projectsPartnered %}
        {{ parent() }}
    {% endblock %}
{% endembed %}

&lt;hr&gt;

{% embed '_partials/_partnerList.twig' with {
    items: craft.entries.section('someOtherSection').all()
}%}
    {% block subItemsBlock %}
        {% set subItems = item.relatedOtherThings.all() %}
        {{ parent() }}
    {% endblock %}
{% endembed %}

{# ==================================
_partnerList.twig.
===================================== #}

{% for item in items %}
    &lt;h3&gt;{{ item.title }}&lt;/h3&gt;
    {% block subItemsBlock %}
        &lt;ul&gt;
            {% for subItem in subItems %}
                &lt;li&gt;{{ subItem.title }}&lt;/li&gt;
            {% endfor %}
        &lt;/ul&gt;
    {% endblock %}
{% endfor %}

</code></pre>
<p><a href="https://twig.symfony.com/doc/3.x/tags/embed.html" rel="nofollow noreferrer">https://twig.symfony.com/doc/3.x/tags/embed.html</a>
<a href="https://twig.symfony.com/doc/3.x/functions/parent.html" rel="nofollow noreferrer">https://twig.symfony.com/doc/3.x/functions/parent.html</a></p>
<p>(Aside - you don't need to prefix private templates with an underscore if they're already inside a directory prefixed with an underscore).</p>

CC BY-SA 4.0
2024-10-02T22:40:36.393Z
— really interesting answer, thanks. The square bracket approach works well for me with my current understanding of includes and this particular scenario, but I certainly looking into embeds too — a whole new world! Really appreciate you sharing this, I have learnt a lot :)
dezbat
CC BY-SA 4.0
2024-10-02T22:42:59.983Z
— to clarify **both of these answers are valid.** The second answer from Mats is slightly more helpful in this case as it's a quicker route with fallbacks for my current skill level.
dezbat
CC BY-SA 4.0
2024-09-30T14:22:57.357Z
2024-09-30T14:28:14.017Z
2024-09-30T14:28:14.017Z
James Smith
<p>I have a template / include that lists different entries. The first template include does this:</p>
<pre><code>  {% include '_partials/_partnerList.twig' with {
        'items': craft.entries.section('partners').orderBy('title').all(),
  } %}
</code></pre>
<p>then _partnerList.twig does something like this, where I loop through and display related entries per 'item'.</p>
<pre><code>{% for item in items %}

{{ item.title }}

      {% for project in item.projectsPartnered.all() %}

      {{ project.title }}

      {% endfor %}

{% endfor %}
</code></pre>
<p>This all works fine, but...</p>
<p><strong>I'd like to be able to reuse my partial by looping through OTHER related entries on different pages. So in order to set up this possibility I tried passing the twig from my 'with' values:</strong></p>
<pre><code>  {% include '_partials/_partnerList.twig' with {
        'items': craft.entries.section('partners').orderBy('title').all(),
        'linkage': 'item.projectsPartnered.all()'
  } %}
</code></pre>
<p>and referencing 'linkage' in my included twig file like so:</p>
<pre><code>{% for item in items %}

{{ item.title }}

      {% for project in linkage %}

      {{ project.title }}

      {% endfor %}

{% endfor %}
</code></pre>
<p>But this fails to work. Neither does</p>
<pre><code>'linkage': 'projectsPartnered.all()' 
</code></pre>
<p>with</p>
<pre><code>{% for project in item.linkage %}
</code></pre>
<p>Perhaps Im misunderstanding what is possible, but Im trying to inject a bit of twig into a statement downstream, if that makes sense...</p>
<p>Any thoughts much appreciated :)</p>

<templating><craft4><include><craft5>
How to pass a chunk of twig from an 'include' statement?
# How to pass a chunk of twig from an 'include' statement?

(Asked by: username_0 on 2024-09-30)

I have a template / include that lists different entries. The first template include does this:
  {% include '_partials/_partnerList.twig' with {
        'items': craft.entries.section('partners').orderBy('title').all(),
  } %}

then _partnerList.twig does something like this, where I loop through and display related entries per 'item'.
{% for item in items %}

{{ item.title }}

      {% for project in item.projectsPartnered.all() %}

      {{ project.title }}

      {% endfor %}

{% endfor %}

This all works fine, but...
I'd like to be able to reuse my partial by looping through OTHER related entries on different pages. So in order to set up this possibility I tried passing the twig from my 'with' values:
  {% include '_partials/_partnerList.twig' with {
        'items': craft.entries.section('partners').orderBy('title').all(),
        'linkage': 'item.projectsPartnered.all()'
  } %}

and referencing 'linkage' in my included twig file like so:
{% for item in items %}

{{ item.title }}

      {% for project in linkage %}

      {{ project.title }}

      {% endfor %}

{% endfor %}

But this fails to work. Neither does
'linkage': 'projectsPartnered.all()' 

with
{% for project in item.linkage %}

Perhaps Im misunderstanding what is possible, but Im trying to inject a bit of twig into a statement downstream, if that makes sense...
Any thoughts much appreciated :)

**Tags:** templating, craft4, include, craft5


---

## 2 answers

### Answer by username_1 on 2024-10-01. Score: 1 | Accepted answer

AFAIK it's not possible to have Twig execute arbitrary code from a string like that – there is the template_from_string() function, but that will only render output, similarly to a macro or include, i.e. not return anything like you need the .all() to do.
However, considering the item variable is redundant outside the loop in the _partnerList.twig template (it's defined inside that template, after all) and the .all() is also redundant outside (as you can easily call it inside the partner list loop), you can omit both of those parts. At that point, you're left with the 'projectsPartnered' field handle – which can be passed as a string variable and used inside the _partnerList.twig template like this:
The include:
{% include '_partials/_partnerList.twig' with {
    items: craft.entries.section('partners').orderBy('title').all(),
    linkage: 'projectsPartnered'
} %}

In the _partnerList.twig template:
{% for item in items %}
    {{ item.title }}

    {% if linkage is defined %}
        {% for project in item[linkage].all() ?? [] %}
            {{ project.title }}
        {% endfor %}
    {% endif %}
{% endfor %}

The key here being the item[linkage].all() part.
Note that I added a couple of defensive measures to the code. First, the {% if linkage is defined %} conditional is to make sure you don't run into an error if the _partnerList.twig template is ever included without supplying a linkage variable. Second, the null coalescing operator (??) after the call to .all() is to make sure the statement defaults to an empty array, instead of throwing an exception, in cases where the linkage variable might refer to a field that doesn't actually exist in the item element's field layout.

> **Comments:**
> **username_0**: — this answer is absolutely spot one.  
> **username_0**: — Beautifully explained too. I do find it frustrating not always understanding how / why certain things operate in Twig (in this case the square bracket syntax), I guess learning by example as here is the best way :)  But would love to know if you recommend any decent Twig / templating education or indeed if you have anything out there.  many thanks  Matt  
> **username_1**: @username_0 I'm happy it was helpful ❤️ I think Twig generally strikes a pretty perfect balance between "real" PHP and a very simplified template language, but the fact that something like `.item[foobar]` works (where `foobar` is a variable referring to an object method or property – in this case a custom field on an entry) is definitely something that comes from the PHP side of things, and it's not something Twig makes apparent. I'd give you some links if I could, but generally I'd advice digging into PHP basics, as once you get an understanding of PHP, Twig kind of opens up a lot.  
> **username_1**: Also, James' answer isn't wrong and in many cases the `{% embed %}` tag (which is admittedly one of the harder Twig tags to wrap one's head around) might be a more robust way to approach problems like this!  

---

### Answer by username_2 on 2024-09-30. Score: 2

What you're trying to do is possible using "variable variables" (i.e., a Twig object with a dynamically named sub-property), however in my opinion a better approach would be to use embed which is ideally suited for this purpose. https://twig.symfony.com/doc/3.x/tags/embed.html
Variable variables
If you want to persist with the "variable variables" approach, it looks like the later versions of Twig (3.15+) now support this via the dot operator - you can pass an expression like this: {% for project in item.(linkage).all() %} - then you'd pass in a string for the linkage variable telling the partial which named property to use, i.e. linkage: 'projectsPartnered'. Earlier versions of Twig need to use the attribute() function for variable variables. https://twig.symfony.com/doc/3.x/functions/attribute.html Though I've often found you can also do it with square bracket syntax instead of dot notation, i.e. item[linkage].all(). I haven't tested all those, because the better solution to your problem is...
Embed
Embeds are better for this in my opinion as they allow for full flexibility via block overrides. You could use the {{ parent() }} function to delegate responsibility for outputting the actual markup to the embed, so you're basically just setting variables to be consumed by the embed - it can work in lots of different ways, but try something like this (I've also added eager loading for the first embed):
{# ==================================
index.twig
===================================== #}

{% embed '_partials/_partnerList.twig' with {
    items: craft.entries.section('partners').with(['projectsPartnered']).orderBy('title').all()
}%}
    {% block subItemsBlock %}
        {% set subItems = item.projectsPartnered %}
        {{ parent() }}
    {% endblock %}
{% endembed %}



{% embed '_partials/_partnerList.twig' with {
    items: craft.entries.section('someOtherSection').all()
}%}
    {% block subItemsBlock %}
        {% set subItems = item.relatedOtherThings.all() %}
        {{ parent() }}
    {% endblock %}
{% endembed %}

{# ==================================
_partnerList.twig.
===================================== #}

{% for item in items %}
    {{ item.title }}
    {% block subItemsBlock %}
        
            {% for subItem in subItems %}
                {{ subItem.title }}
            {% endfor %}
        
    {% endblock %}
{% endfor %}


https://twig.symfony.com/doc/3.x/tags/embed.html
https://twig.symfony.com/doc/3.x/functions/parent.html
(Aside - you don't need to prefix private templates with an underscore if they're already inside a directory prefixed with an underscore).

> **Comments:**
> **username_0**: — really interesting answer, thanks. The square bracket approach works well for me with my current understanding of includes and this particular scenario, but I certainly looking into embeds too — a whole new world! Really appreciate you sharing this, I have learnt a lot :)  
> **username_0**: — to clarify **both of these answers are valid.** The second answer from Mats is slightly more helpful in this case as it's a quicker route with fallbacks for my current skill level.  

---

