twig模板引擎使用php,在Yii框架中使用PHP模板引擎Twig的例子

/*

* This file is an extension of Twig.

*

* (c) 2010 lfyzjck

*/

/**

* parser widget tag in Yii framework

*

* {% beginwidget 'CActiveForm' as form %}

*    content of form

* {% endwidget %}

*

*/

class Yii_WidgetBlock_TokenParser extends Twig_TokenParser

{

/**

* Parses a token and returns a node.

*

* @param Twig_Token $token A Twig_Token instance

*

* @return Twig_NodeInterface A Twig_NodeInterface instance

*/

public function parse(Twig_Token $token)

{

$lineno = $token->getLine();

$stream = $this->parser->getStream();

$name = $stream->expect(Twig_Token::STRING_TYPE);

if($stream->test(Twig_Token::PUNCTUATION_TYPE)){

$args = $this->parser->getExpressionParser()->parseHashExpression();

}

else{

$args = new Twig_Node_Expression_Array(array(), $lineno);

}

$stream->expect(Twig_Token::NAME_TYPE);

$assign = $stream->expect(Twig_Token::NAME_TYPE);

$stream->expect(Twig_Token::BLOCK_END_TYPE);

$body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);

$stream->expect(Twig_Token::BLOCK_END_TYPE);

return new Yii_Node_WidgetBlock(array(

'alias' => $name->getValue(),

'assign' => $assign,

), $body, $args, $lineno, $this->getTag());

}

/**

* Gets the tag name associated with this token parser.

*

* @param string The tag name

*/

public function getTag()

{

return 'beginwidget';

}

public function decideBlockEnd(Twig_Token $token)

{

return $token->test('endwidget');

}

}

class Yii_Node_WidgetBlock extends Twig_Node

{

public function __construct($attrs, Twig_NodeInterface $body, Twig_Node_Expression_Array $args = NULL, $lineno, $tag)

{

$attrs = array_merge(array('value' => false),$attrs);

$nodes = array('args' => $args, 'body' => $body);

parent::__construct($nodes, $attrs, $lineno,$tag);

}

public function compile(Twig_Compiler $compiler)

{

$compiler->addDebugInfo($this);

$compiler->write('$context["'.$this->getAttribute('assign')->getValue().'"] = $context["this"]->beginWidget("'.$this->getAttribute('alias').'",');

$argNode = $this->getNode('args');

$compiler->subcompile($argNode)

->raw(');')

->raw("\n");

$compiler->indent()->subcompile($this->getNode('body'));

$compiler->raw('$context["this"]->endWidget();');

}

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值