Home » Php » php – symfony2 twig and multiple levels of subfolders

php – symfony2 twig and multiple levels of subfolders

Posted by: admin April 23, 2020 Leave a comment

Questions:

I find that including a template with this path works fine

{% include 'AcmeDemoBundle:TemplateArchive:view.html.twig' with {'data': c.data} %}

While this is seemingly not allowed:

{% include 'AcmeDemoBundle:TemplateArchive:6:view.html.twig' with {'data': c.data} %}

I am in other words trying to reach templates that I have sorted down into a subfolder structure in my bundle/resources/views/ folder.

If I am not allowed to drill any deeper than the regular one-level-inclusion as of my first line, is there another/better way of structuring these template files?

(the folder name ‘6’ represents a template id from the database which I would like to include, it needs to be dynamic and sorted in folders nicely like that…).

I have tried naming my templates-folder ‘t6’ but no difference, the “number with no leading letters” is not the issue here…

How to&Answers:

What about

{% include 'AcmeDemoBundle:TemplateArchive:6/view.html.twig' with {'data': c.data} %}

Answer:

Both is working:

AcmeDemoBundle:TemplateArchive:6/view.html.twig
AcmeDemoBundle:TemplateArchive/6:view.html.twig

Answer:

As of Symfony 2.2 you can also use Namespaced paths:

{% include '@AcmeDemo/TemplateArchive/6/bar.html.twig' with {'data': c.data} %}

You can even define your own Namespaces:

# app/config/config.yml
twig:
    # ...
    paths:
        "%kernel.root_dir%/../src/Acme/DemoBundle/Resources/views/TemplateArchive": TemplateArchive

And then use it like:

{% include '@TemplateArchive/6/view.html.twig' with {'data': c.data} %}

This also works in controllers (with custom Namespaces too):

// TemplateArchiveController.php
return $this->render('@TemplateArchive/6/view.html.twig', ['data' => $c.getData()]);

From [Symfony Cookbook: Namespaced paths]:

As an added bonus, the namespaced syntax is faster.