Import content between Twig files
How can I get a Twig file that imports some of this content from a second Twig file in the same or subdirectory?
I am developing a project where multiple Twig files share content and I am trying to avoid copying and pasting content between Twig files.
So, I want to have a subdirectory with shared markup and just "import" into the appropriate 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.
source to share
When you are include
, it needs to know the namespace where it is located. When you execute ::
like in {% extends "::base.html.twig" %}
, it comes from app/Resources/views
your application directory .
See: Template Naming and Locations Symfony Documentation
If yours import.list.html.twig
is in the kit, you will need to identify it correctly. For example, if you have a StockBundle and Resources / Views in that bundle with your own template base.html.twig
, you would have
{% include 'StockBundle::base.html.twig' %}
If you had, say, a Stock folder inside this bundle (attached to your StockController) and a template import.list.html.twig
, you would have
{% include 'StockBundle:Stock:import.list.html.twig' %}
{% include '@Stock/base.html.twig' %}
{% include '@Stock/Stock/import.list.html.twig' %}
Here is another good link for Best Symfony Templates Examples
Note
As of Symfony 2.2, you can use include()
function and this is the preferred way to include templates:
{{ include('@Stock/base.html.twig') }}
{{ include('@Stock/Stock/import.list.html.twig') }}
source to share
Try the following:
{% include 'StockBundle:Stock:import.list.html.twig' %}
instead:
{% include 'import.list.html.twig' %}
http://symfony.com/doc/current/book/templating.html#including-templates
source to share