Skip to content

Instantly share code, notes, and snippets.

@lode
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lode/ecc27fe1ededc9b4a219 to your computer and use it in GitHub Desktop.
Save lode/ecc27fe1ededc9b4a219 to your computer and use it in GitHub Desktop.
Automatic partials
<?php
/**
* a controller vm
* w/o explicit reference to any data
*/
class controller {}
$controller_tpl = '
<h1>The team</h1>
{{> members_collection}}
';
/**
* partial vms
* with their own data
*/
class members_collection {
public $data;
public function __toString() {
$template = '
<ul>
{{# data}}
{{> members_object}}
{{/ data}}
</ul>
';
return mustache::parse($template, $this);
}
public function __construct() {
$this->data = array(
new members_object('Foo Bar'),
new members_object('Bar Baz'),
new members_object('Baz Foo'),
);
}
}
class members_object {
public $name;
public function __toString() {
$template = '
<li>{{name}}</li>
';
return mustache::parse($template, $this);
}
public function __construct($name='Mr. X') {
$this->name = $name;
}
}
/**
* rendering
*/
class mustache {
public static function parse($template, $data) {
require_once 'Mustache/Autoloader.php';
Mustache_Autoloader::register();
$mustache_options = array(
'partials' => array(
'members_collection' => new members_collection,
'members_object' => new members_object,
),
);
$mustache = new Mustache_Engine($mustache_options);
return $mustache->render($template, $data);
}
}
echo mustache::parse($controller_tpl, new controller);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment