Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Twig training 2
{{ macro_buttons.button1('...') }}
<?php
class Project_Set_Node extends Twig_Node
{
public function __construct($name, Twig_Node_Expression $value, $lineno)
{
parent::__construct(array('value' => $value), array('name' => $name), $lineno);
}
public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('$context[\''.$this->getAttribute('name').'\'] = ')
->subcompile($this->getNode('value'))
->raw(";\n")
;
}
}
<?php
class Project_Set_TokenParser extends Twig_TokenParser
{
public function parse(Twig_Token $token)
{
$lineno = $token->getLine();
$name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
$this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, '=');
$value = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
return new Project_Set_Node($name, $value, $lineno, $this->getTag());
}
public function getTag()
{
return 'set';
}
}
<?php
// Filtres :
$twig->addFilter('rot13', new Twig_Filter_Function('str_rot13'));
// ou
$twig->addFilter('rot13', new Twig_Filter_Function('SomeClass::rot13Filter'));
// ou
$twig->addFilter('rot13', new Twig_Filter_Method($this,'rot13Filter'));
// Filtres dynamiques :
$twig->addFilter('*_path', new Twig_Filter_Function('twig_path'));
function twig_path($name, $arguments)
{
// ...
}
// Exemple :
// {{ 'shoes_ref_abc' | shoes_path }}
// will call
twig_path('shoes', 'shoes_ref_abc');
<?php
$twig->addTokenParser(new Project_Set_TokenParser());
<?php
class Project_Twig_Extension extends Twig_Extension
{
public function getFilters()
{
return array(
'rot13' => new Twig_Filter_Method($this, 'rot13Filter'),
);
}
public function rot13Filter($string)
{
return str_rot13($string);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment