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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With