PHP Mustache 2.1 partial loading NOT based on the filename

删除回忆录丶 提交于 2019-12-17 19:04:05

问题


Is there a way to load partials based on an array of filename values?

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)

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'
);

which would translate to: views/folder1/somefile.mustache.


回答1:


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;
    }
}

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);


来源:https://stackoverflow.com/questions/14878970/php-mustache-2-1-partial-loading-not-based-on-the-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!