Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Forked from fprochazka/BasePresenter.php
Created April 14, 2011 13:04
Show Gist options
  • Save Mikulas/919433 to your computer and use it in GitHub Desktop.
Save Mikulas/919433 to your computer and use it in GitHub Desktop.
Twig Macro
<?php
public function templatePrepareFilters($template) {
$template->registerFilter($latte = new Nette\Templates\LatteFilter());
TwigMacro::register($latte->getHandler());
}
<?php
use Nette\Templates\LatteMacros;
use Nette\Debug;
/**
* @author Pavel Kalvoda
* @author Filip Procházka
*/
class TwigMacro
{
const SEPARATOR = '.';
/** @var Nette\Templates\LatteMacros */
protected static $latte;
/**
* @param Nette\Templates\LatteMacros $latte
*/
public static function register(LatteMacros $latte)
{
$latte->macros['~'] = '<?php %' . __CLASS__ . '::expand% ?>';
$latte->macros['~$'] = '<?php %' . __CLASS__ . '::expand% ?>';
self::$latte = $latte;
}
/**
* @param mixed $path
* @param mixed $modifiers
* @return string
*/
public static function expand($path, $modifiers)
{
$frags = explode(self::SEPARATOR, $path);
$result = __CLASS__ . '::travel($' . array_shift($frags) . ', ' . var_export($frags, TRUE) . ')';
return 'echo ' . self::$latte->formatModifiers($result, $modifiers). ';';
}
/**
* @param object|array $element
* @param array $path
* @return mixed
*/
public static function travel($element, array $path = array())
{
foreach ($path as $leaf) {
if ((is_array($element) || $element instanceof \ArrayAccess) && isset($element[$leaf])) { // http://www.php.net/manual/en/function.is-array.php#48083
$element = $element[$leaf];
continue;
} elseif (is_object($element)) {
if (isset($element->$leaf)) {
$element = $element->$leaf;
continue;
} elseif (method_exists ($object, $method = "get" . ucfirst($leaf))) {
$element = $element->$method();
continue;
}
}
throw new \InvalidStateException("Given structure doesn't contain specified offset, property, or getter method.");
}
return $element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment