Example of using the PHP template engine Twig in the Yii framework _ php instance

Source: Internet
Author: User
Tags php template
This article describes how to use the PHP template engine Twig in the Yii framework. Twig is a simple PHP template engine, for more information, see Twig, a fast, secure, and flexible PHP template engine. It has many built-in filters and tags and supports template inheritance, it allows you to describe your template with the simplest code. Its syntax is very similar to the template engine Jinjia in Python and the template syntax of Django. For example, when we need to output variables in PHP and escape them, the syntax is cumbersome:

The Code is as follows:




However, in Twig, you can write as follows:

The Code is as follows:


{Var }}
{Var | escape }}
{Var | e }{# shortcut to escape a variable #}


Traverse the array:

The Code is as follows:


{% For user in users %}
* {User. name }}
{% Else %}
No user has been found.
{% Endfor %}

However, the integration of Twig in Yii Framework will cause some trouble. The official website already has a solution that can integrate Twig, so I will not go into details here. However, because Twig does not support PHP syntax, some expressions may encounter difficulties. For example, we often write this when writing a Form View:

The Code is as follows:


BeginWidget ('cactiveform');?>
Login



  • Label ($ model, 'username');?>
    TextField ($ model, 'username');?>


  • Label ($ model, 'Password');?>
    PasswordField ($ model, 'Password');?>


  • Login


Error ($ model, 'Password');?>
EndWidget ();?>


However, this syntax cannot be expressed in twig. Therefore, we want to extend the Twig function so that it can support our custom widget labels, then it is automatically parsed into the code we need. A total of two classes are required: TokenParser and Node. The Code is as follows:

The Code is as follows:


/*
* 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-> CT (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-> CT (Twig_Token: NAME_TYPE );
$ Assign = $ stream-> CT (Twig_Token: NAME_TYPE );
$ Stream-> reverse CT (Twig_Token: BLOCK_END_TYPE );

$ Body = $ this-> parser-> subparse (array ($ this, 'includeblockend'), true );
$ Stream-> reverse CT (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 ();');
}
}
?>


Then add our Syntax Parsing class in the place where the Twig is initialized:

The Code is as follows:


$ Twig-> addTokenParser (new Yii_WidgetBlock_TokenParser );


Then we can write this in the twig template:

The Code is as follows:


{% Beginwidget 'cactiveform' as form %}



  • {Form. label (model, 'username ')}}
    {Form. textField (model, 'username ')}}


  • {Form. label (model, 'Password ')}}
    {Form. passwordField (model, 'Password ')}}


{% Endwidget %}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.