Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import content between Twig files

How can I have a Twig file which imports some of it's content from a second Twig file in the same or a sub directory?

I am developing a project where multiple Twig files have content in common and I'm trying to avoid copying and pasting content between Twig files.

So, I want to have a subdirectory containing the shared markup and simply "import" into the relevant sections of the main Twig files.

With import.list.html.twig in the same directory as the main Twig file, I tried the following:

{% extends "::base.html.twig" %}

{% block title %}StockBundle:StockController:index{% endblock %}

{% block body %}
<h1>Welcome to the StockController:List page</h1>

{% for stock in stocks %}
    <div class='list'>
        <div class='each stock'>
            <span class='name'>{{ stock.name }}</span>
            <span class='desc'>{{ stock.description }}</span>
            <span class='balc'>{{ stock.balance }}</span>
            <span class='edit'>
                <a href="{{ path('stock_edit', {'id':stock.id}) }}">edit</a>
            </span>
        </div>
    </div>
{% endfor %}

{% include 'import.list.html.twig' %}

{% endblock %}

... but I got the following error:

Unable to find template "import.list.html.twig" in ::base.html.twig at line 10.
like image 676
sisko Avatar asked Dec 14 '25 07:12

sisko


1 Answers

When you include it needs to know the namespace of where it is located. When you do ::, as in {% extends "::base.html.twig" %}, it comes from the app/Resources/views directory of your application.

See: Template Naming and Locations Symfony documentation

If your import.list.html.twig is in a bundle, you'll have to define that properly. For instance, if you have StockBundle and a Resources/views directory in that bundle with its own base.html.twig template, you would have

{% include 'StockBundle::base.html.twig' %}

If you had, say, a Stock folder inside that bundle (attached to your StockController) and an import.list.html.twig template, you would have

{% include 'StockBundle:Stock:import.list.html.twig' %}

Note via Registered Namespaced Twig Paths that you can also use a namespaced path instead. They're actually faster as well. So the above would instead be

{% include '@Stock/base.html.twig' %}
{% include '@Stock/Stock/import.list.html.twig' %}

Here's another good reference for Symfony template best practices

NOTE

Since Symfony 2.2, you can use the include() function, and this is the preferred way to include templates:

{{ include('@Stock/base.html.twig') }}
{{ include('@Stock/Stock/import.list.html.twig') }}
like image 165
Jason Roman Avatar answered Dec 16 '25 21:12

Jason Roman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!