Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Forked from PJK/BasePresenter.php
Created April 14, 2011 12:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fprochazka/919350 to your computer and use it in GitHub Desktop.
Save fprochazka/919350 to your computer and use it in GitHub Desktop.
TwigMacro
<?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 = $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;
} elseif ($element instanceof \ArrayAccess) {
$element = $element[$leaf];
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