如何在模板引擎 TWIG 中从完整路径加载模板

2022-01-22 00:00:00 templates php twig template-engine

我想知道如何从模板的完整路径加载模板(例如 FILE 常量).

I'm wondering how to load a template from it's full path (like FILE constant give).

实际上你必须像这样为模板设置一个根"路径:

Actually you have to set a "root" path for template like this :

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
   'cache' => '/path/to/compilation_cache',
));

然后:

$template = $twig->loadTemplate('index.html');
echo $template->render(array('the' => 'variables', 'go' => 'here'));

我想用完整路径而不是文件名来调用 loadTemplate 方法.

I want to call the loadTemplate method with a full path and not the just the name of the file.

我该怎么办?

我不想为这样的事情创建自己的加载器..

I don't want to create my own loader for such an thing..

谢谢

推荐答案

就这样吧:

$loader = new Twig_Loader_Filesystem('/');

这样 ->loadTemplate() 将相对于 / 加载模板.

So that ->loadTemplate() will load templates relatively to /.

或者,如果您希望能够同时加载具有相对路径和绝对路径的模板:

Or if you want to be able to load templates both with relative and absolute path:

$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));

相关文章