Skip to content

Instantly share code, notes, and snippets.

@alister
Last active January 26, 2018 09:28
Show Gist options
  • Save alister/2e316cc3ed6ccaf8c131f0d6a3cf3c72 to your computer and use it in GitHub Desktop.
Save alister/2e316cc3ed6ccaf8c131f0d6a3cf3c72 to your computer and use it in GitHub Desktop.
twigTombstone
class TwigExtension extends \Twig_Extension
{
// ....
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'tombstone',
array($this, 'twigTombstone'),
array('needs_environment' => true)
),
);
}
public function twigTombstone(\Twig_Environment $env, $date, $author, $label = ''): void
{
if ($label) {
$label .= ' ';
}
$label .= $this->getTwigTemplateName();
tombstone($date, $author, $label);
}
/**
* Return Twig-template-filename:lineno, if we can find it
*
* @see https://stackoverflow.com/a/44648744/6216
*/
private function getTwigTemplateName(): string
{
foreach (debug_backtrace() as $trace) {
if (isset($trace['object'])
&& (strpos($trace['class'], 'TwigTemplate') !== false)
&& 'Twig_Template' !== get_class($trace['object'])
) {
return $trace['object']->getTemplateName() . ":{$trace['line']}";
}
}
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment