Kohana 3.2 + Twig Issues
I'm u开发者_开发知识库sing this module to integrate Twig into my small Kohana project. I'm facing the following issues:
- How to use helpers/custom functions?
- How to use Kohana core functions, ex.
__()
for translating, functions to create URLs?
If anybody has any suggestions, I'd be delighted.
I not used exactly this Twig integration, but strategy as follow (1. helpers/custom functions): Add in your config/twig.php
'extensions' => array (
'Twig_Extension_Escaper', // native twig escaper
'Twig_Extension_Optimizer', // native twig optimizer
'View_Extensions', // your custom extensions
)
Then create classes/view/Extensions.php
class View_Extensions extends Twig_Extension {
public function getTokenParsers() {
return array(
new View_Extension_Html_TokenParser(), // all HTML methods
);
}
public function getFilters() {
return array(
'limit_words' => new Twig_Filter_Function('Text::limit_words'), // {{ text|limit_words(25) }}
);
}
public function getName() {
return 'view_extension';
}
}
And create minimal HTML token parser
class View_Extension_Html_TokenParser extends View_Extension_Helper_TokenParser {
public function getTag() {
return 'html'; // lowercase as all in twig
}
}
Create basic helper
abstract class View_Extension_Helper_TokenParser extends Twig_TokenParser {
public function parse(Twig_Token $token) {
$lineno = $token->getLine();
// Methods are called like this: html.method, expect a period
$this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, '.');
// Find the html method we're to call
$method = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
$params = $this->parser->getExpressionParser()->parseMultiTargetExpression();
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
return new View_Extension_Helper_Node(array('expression' => $params), array('method' => $method), $lineno, $this->getTag());
}
}
And the last - node helper
class View_Extension_Helper_Node extends Twig_Node {
protected $cs_tags = array( // your case sensitive tags
'html' => 'HTML',
);
public function compile(Twig_Compiler $compiler) {
$params = $this->getNode('expression')->getIterator();
$nodeTag = $this->getNodeTag();
$nodeTag = isset($this->cs_tags[strtolower($nodeTag)]) ? $this->cs_tags[strtolower($nodeTag)] : $nodeTag;
// Output the route
$compiler->write('echo ' . $nodeTag . '::' . $this->getAttribute('method') . '(');
foreach ($params as $i => $row) {
$compiler->subcompile($row);
if (($params->count() - 1) !== $i) {
$compiler->write(',');
}
}
$compiler->write(')')->raw(';');
}
}
So after the last you can use all HTML methods like a {% html.anchor "/anchor" %}
I hope there no errors.
精彩评论