Wednesday, 15 June 2011

PHP Mustache 2.1 partial loading NOT based on the filename -



PHP Mustache 2.1 partial loading NOT based on the filename -

is there way load partials based on array of filename values?

currently if write {{> sidebar}} views/sidebar.mustache. (based on template loader class can specify templates)

ideally want {{> sidebar}} variable name , not file name.

what want accomplish sidebar partial not based on filename, if pass loader:

$partials = array( 'sidebar' => 'folder1/somefile' );

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

you can adding new partials loader implementation. create "alias loader", stores 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); } homecoming parent::load($this->aliases[$name]); } public function settemplates(array $templates) { $this->aliases = $templates; } public function settemplate($name, $template) { $this->aliases[$name] = $template; } }

then, set 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 pass aliases loader constructor, or set them later on loader or engine instance:

$loader = new filesystemaliasloader('path/to/partials', $partials); $loader->settemplates($partials); $mustache->setpartials($partials);

php partial-views mustache

No comments:

Post a Comment