Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 525
feketegy Avatar asked Feb 14 '13 16:02

feketegy


Video Answer


1 Answers

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);
like image 72
bobthecow Avatar answered Sep 28 '22 11:09

bobthecow