Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig- Include Template from other Directory

Tags:

twig

Is it possible to include a template with {% include %} which is outside from the template path defined with:

$template = $twig->loadTemplate('example.tpl'); 

I'm asking it because this line doesn't work:

{% include '.../example/navbar_left.tpl' %}
like image 241
user1766080 Avatar asked Oct 22 '12 19:10

user1766080


3 Answers

No, it's not possible using Twig_Loader_Filesystem, because it explicitly rejects template names which have .. inside. This can be verified into the definition of function validateName($name) inside file Twig/lib/Twig/Loader/Filesystem.php.

The only clean solution I can think of, if you need to access a template outside the path, is to create your own loader.

A workaround that does work, is defining a symbolic link inside the folder actually registered with Twig_Loader_Filesystem, pointing to the directory you want to access. Be careful with this method, point the link to a safe place.

like image 87
Nicolás Ozimica Avatar answered Oct 19 '22 20:10

Nicolás Ozimica


You can add your path to the Twig loader (Filesystem loader) see last reply from Fabien (addPath method is what you need) https://github.com/symfony/symfony/issues/1912

like image 30
olegkhuss Avatar answered Oct 19 '22 20:10

olegkhuss


You can add more paths by following : https://symfony.com/doc/3.4/templating/namespaced_paths.html

config.yml

# Twig Configuration
twig:
  paths:
    '%kernel.root_dir%/../src/AppBundle/Resources/views': AppBundle
    '%kernel.root_dir%/../web/': 'WEB_DIR_DIST' #your new custom path

someFile.html.twig

<script>{{ source('@WEB_DIR_DIST' ~ 'custom.js') }}</script>
like image 5
max4ever Avatar answered Oct 19 '22 20:10

max4ever