[英]How to load a template from full path in the template engine TWIG
我想知道如何从它的完整路径加载模板(如FILE常量给定)。
实际上你必须像这样为模板设置一个“根”路径:
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 方法,而不仅仅是文件名。
我能怎么做?
我不想为这样的事情创建自己的装载机..
谢谢
只需这样做:
$loader = new Twig_Loader_Filesystem('/');
这样 ->loadTemplate() 将相对于/
加载模板。
或者,如果您希望能够使用相对路径和绝对路径加载模板:
$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));
扩展加载器比修改库更好:
<?php
/**
* Twig_Loader_File
*/
class Twig_Loader_File extends Twig_Loader_Filesystem
{
protected function findTemplate($name)
{
if(isset($this->cache[$name])) {
return $this->cache[$name];
}
if(is_file($name)) {
$this->cache[$name] = $name;
return $name;
}
return parent::findTemplate($name);
}
}
这是一个加载给定绝对(或非)路径的加载器:
<?php
class TwigLoaderAdapter implements Twig_LoaderInterface
{
protected $paths;
protected $cache;
public function __construct()
{
}
public function getSource($name)
{
return file_get_contents($this->findTemplate($name));
}
public function getCacheKey($name)
{
return $this->findTemplate($name);
}
public function isFresh($name, $time)
{
return filemtime($this->findTemplate($name)) < $time;
}
protected function findTemplate($path)
{
if(is_file($path)) {
if (isset($this->cache[$path])) {
return $this->cache[$path];
}
else {
return $this->cache[$path] = $path;
}
}
else {
throw new Twig_Error_Loader(sprintf('Unable to find template "%s".', $path));
}
}
}
?>
这对我有用(Twig 1.x):
final class UtilTwig
{
/**
* @param string $pathAbsTwig
* @param array $vars
* @return string
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public static function renderTemplate(string $pathAbsTwig, array $vars)
{
$loader = new Twig_Loader_Filesystem([''], '/');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate($pathAbsTwig);
$mailBodyHtml = $template->render($vars);
return $mailBodyHtml;
}
}
用法:
$htmlBody = UtilTwig::renderTemplate('/absolute/path/to/template.html.twig', [
'some' => 'var',
'foo' => 'bar'
]);
在 Symfony 的(版本 5.4)配置中添加新的核心路径到包含模板的文件夹。
twig:
default_path: '%kernel.project_dir%/templates'
paths:
'%kernel.project_dir%/src/Service/SendEmail/EmailTpl': EmailTpl
现在你可以渲染模板了。
在 controller:
$this->render('@EmailTpl/bobo_reg.html.twig')
在任何其他地方:
$content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.