Example of using PHP template engine twig in the YII framework _php instance

Source: Internet
Author: User
Tags button type php template tag name yii

Twig is a fast, secure, flexible PHP template engine that has a built-in number of filter and tags and supports template inheritance, allowing you to use the simplest code to describe your template. His syntax is very similar to that of the template engine Jinjia in Python and the template syntax for Django. For example, when we need to output variables in PHP and escape them, the syntax is cumbersome:

Copy Code code as follows:

<?php Echo $var?>
<?php echo htmlspecialchars (\ $var, ent_quotes, ' UTF-8 ')?>

But you can write this in twig:
Copy Code code as follows:

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

To traverse an array:
Copy Code code as follows:

{% for user in users%}
* {{User.Name}}
{% Else%}
No user has been found.
{% ENDFOR%}

But in the YII framework integration Twig will encounter a bit of trouble, the official web site has been able to integrate Twig program, so here I do not repeat. But because PHP syntax is not supported in twig, there are difficulties with some expressions, such as when we write a form's view:

Copy Code code as follows:

<?php $form = $this->beginwidget (' cactiveform ');?>
<span>Login</span>
<ul>
<li>
<?php echo $form->label ($model, ' username ');?>
<?php echo $form->textfield ($model, ' username ');?>

</li>

<li>
<?php echo $form->label ($model, ' password ');?>
<?php echo $form->passwordfield ($model, ' password ');?>

</li>

<li class= "Last" >
<button type= "Submit" >Login</button>

</li>

</ul>
<?php echo $form->error ($model, ' password ');?>
<?php $this->endwidget ();?>


But such a grammar cannot be expressed in twig, so you want to extend the functionality of the twig so that he can support our custom widget tags and automatically parse into the code we need. A total of two classes are required: Tokenparser and node, the following directly code:
Copy Code code as follows:

<?php
/*
* This file is a extension of Twig.
*
* (c) lfyzjck
*/

/**
 * Parser widget tag in Yii framework
 *
 * {% beginwidget ' cactiveform ' as form%}
&nbs p;*    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
 & nbsp;   *
     * @return twig_nodeinterface A twig_nodeinterface instance
 & nbsp;   */
    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::P unctuation_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)
    {
  & nbsp;     $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 classes where twig initializes:
Copy Code code as follows:

$twig->addtokenparser (new Yii_widgetblock_tokenparser);

Then we can write this in the twig template:
Copy Code code as follows:

{% Beginwidget ' cactiveform ' as form%}
<ul>
<li>
{{Form.label (model, ' username ')}}
{{Form.textfield (model, ' username ')}}
</li>
<li>
{{Form.label (model, ' Password ')}}
{{Form.passwordfield (model, ' Password ')}}
</li>
</ul>
{% 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.