Skip to content

Instantly share code, notes, and snippets.

@julesbou
Created February 2, 2011 15:38
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 julesbou/807863 to your computer and use it in GitHub Desktop.
Save julesbou/807863 to your computer and use it in GitHub Desktop.
Symfony2 Mustache improvements
<?php
// Mustache only support single dimensional array
// With this patch, we can pass an array of objects to Mustache::renderString
$string = '{{var.foo}}';
$parameters = array('var' => new Object());
class Object
{
protected $foo = 'bar';
public function getFoo()
{
return $this->foo;
}
}
$replacer = function ($match) use ($parameters)
{
if (false !== strpos($match[1], '.')) {
$matches = explode('.', $match[1]);
$param = $parameters[$matches[0]];
unset($matches[0]);
foreach($matches as $m) {
$getter = 'get'.ucfirst($m);
if (!method_exists($param, $getter)) {
return $match[0];
}
$param = $param->$getter();
}
return $param;
} else {
return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
}
};
echo preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
?>
<?php
// Mustache only support single dimensional array
// With this patch, we can pass multi-dimensional array to Mustache::renderString
$string = '{{var.foo}}';
$parameters = array('var' => array('foo' => 'bar'));
$replacer = function ($match) use ($parameters)
{
if (false !== strpos($match[1], '.')) {
$matches = explode('.', $match[1]);
$param = $parameters;
foreach($matches as $m) {
if (!isset($param[$m])) {
return $match[0];
}
$param = $param[$m];
}
return $param;
} else {
return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
}
};
echo preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment