Created
February 2, 2011 15:38
-
-
Save julesbou/807863 to your computer and use it in GitHub Desktop.
Symfony2 Mustache improvements
This file contains 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 | |
// 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); | |
?> |
This file contains 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 | |
// 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