PHP Mustache 2.1部分加载不是基于文件名 [英] PHP Mustache 2.1 partial loading NOT based on the filename
问题描述
是否有一种基于文件名值数组加载部分的方法?
Is there a way to load partials based on an array of filename values?
当前,如果我编写此{{> sidebar}}
,它将查找views/sidebar.mustache
. (基于模板加载程序类,我可以在其中指定在何处查找模板)
Currently if I write this {{> sidebar}}
it will look for views/sidebar.mustache
. (based on the template loader class where I can specify where to look for the templates)
理想情况下,我希望{{> sidebar}}
是变量名而不是文件名.
Ideally I want that {{> sidebar}}
would be a variable name and not a file name.
如果要传递给加载程序,我想实现的是不基于文件名查找侧边栏部分:
What I want to achieve is to look for the sidebar partial not based on the filename, if I pass to the loader:
$partials = array(
'sidebar' => 'folder1/somefile'
);
将会翻译为:views/folder1/somefile.mustache
.
推荐答案
您可以通过添加新的partials loader实现轻松地做到这一点.您可以制作一个别名加载器",用于存储那些模板引用:
You can easily do this by adding a new partials loader implementation. You could make an "alias loader", which stores those template references:
class FilesystemAliasLoader extends Mustache_Loader_FilesystemLoader implements Mustache_Loader_MutableLoader
{
private $aliases = array();
public function __construct($baseDir, array $aliases = array())
{
parent::__construct($baseDir);
$this->setTemplates($aliases);
}
public function load($name)
{
if (!isset($this->aliases[$name])) {
throw new Mustache_Exception_UnknownTemplateException($name);
}
return parent::load($this->aliases[$name]);
}
public function setTemplates(array $templates)
{
$this->aliases = $templates;
}
public function setTemplate($name, $template)
{
$this->aliases[$name] = $template;
}
}
然后,您将其设置为partials loader:
Then, you would set that as the partials loader:
$partials = array(
'sidebar' => 'folder1/somefile'
);
$mustache = new Mustache_Engine(array(
'loader' => new Mustache_Loader_FilesystemLoader('path/to/templates'),
'partials_loader' => new FilesystemAliasLoader('path/to/partials'),
'partials' => $partials,
));
...或者您可以将别名传递给加载器构造函数,或者甚至可以稍后在加载器或引擎实例上设置它们:
... or you could pass the aliases to the loader constructor, or you could even set them later on the loader or engine instance:
$loader = new FilesystemAliasLoader('path/to/partials', $partials);
$loader->setTemplates($partials);
$mustache->setPartials($partials);
这篇关于PHP Mustache 2.1部分加载不是基于文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!