Twig-包含来自其他目录的模板
是否可以包含Twig-包含来自其他目录的模板,twig,Twig,是否可以包含{%include%}的模板,该模板位于以下定义的模板路径之外: $template = $twig->loadTemplate('example.tpl'); 我这么问是因为这条线不行: {% include '.../example/navbar_left.tpl' %} 不,不可能使用Twig\u Loader\u文件系统,因为它明确拒绝包含。的模板名称。这可以在文件Twig/lib/Twig/Loader/Filesystem.php中的函数validateNam
{%include%}
的模板,该模板位于以下定义的模板路径之外:
$template = $twig->loadTemplate('example.tpl');
我这么问是因为这条线不行:
{% include '.../example/navbar_left.tpl' %}
不,不可能使用
Twig\u Loader\u文件系统
,因为它明确拒绝包含。
的模板名称。这可以在文件Twig/lib/Twig/Loader/Filesystem.php中的函数validateName($name)
的定义中进行验证
如果需要访问路径之外的模板,我能想到的唯一干净的解决方案是
一个可行的解决方法是在实际注册到Twig\u Loader\u文件系统的文件夹中定义一个符号链接,指向您要访问的目录。小心使用此方法,将链接指向安全位置。您可以将路径添加到细枝加载程序(文件系统加载程序)
请参阅Fabien的最后回复(addPath方法是您所需要的)
可以通过符号链接进行
Symfony3示例
从src/AppBundle/Resources/views/Admin
Ubuntu:
ln -s ./../../../../../web/admin/_index-import-body.html index-import-body.html.twig
窗口:
mklink index-import-body.html.twig ./../../../../../web/admin/_index-import-body.html
然后像往常一样,在twig文件中包含索引import body.html.twig
{% include '@App/Admin/index-import-body.html.twig' %}
您可以通过以下方式添加更多路径:
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>
{{source('@WEB\u DIR\u DIST'~'custom.js')}
您可以将第二条路径添加到twig.yaml(symfony 4.4)
然后只需使用名称{%include'navbar\u left.tpl%}
是include
范围之外的/app/目录吗?这应该是正确的答案。它不是一种变通方法,支持问题中提到的用例。
twig:
paths:
- '%kernel.project_dir%/templates'
- '%kernel.project_dir%/example'