Last active
August 29, 2015 14:04
-
-
Save lode/ecc27fe1ededc9b4a219 to your computer and use it in GitHub Desktop.
Automatic partials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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