render_partial

The render_partial function will render a template outside of the current context.

Consider the following template:

{# @mynamespace/article.twig #}

<article>
    <a href="{{ link }}">
        <header>
            <h1>{{ title }}</h1>
        </header>
        <div class="body">{{ text }}</div>
    </a>
</article>

This would work fine if you normally use this template directly from php like so:

View::render('@mynamespace/article', $article->toArray());

Now imagine that you want to render this template inside a loop:

{% for article in articles %}
    {% include '@mynamespace/article.twig' %}
{% endfor %}

The variables you would want to use in the template would now be bound to "article" and link would in this case be located on article.link.

But the render_partial function will, behind the scenes, use View::render() to render the template:

{% for article in articles %}
    {{ render_partial('@mynamespace/article', article.toArray())

    {# Or if "article" is an array #}

    {{ render_partial('@mynamespace/article', article)
{% endfor %}

{# The template will be render outside of the scope as if "article" was injected as the template data #}

This would be equivalent to:

View::render('@mynamespace/article', $article->toArray());

Last updated