Home php教程 php手册 在Yii框架中使用PHP模板引擎Twig的例子

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

Jun 13, 2016 am 09:33 AM
twig yii

Twig是一款快速、安全、灵活的PHP模板引擎,它内置了许多filter和tags,并且支持模板继承,能让你用最简洁的代码来描述你的模板。他的语法和Python下的模板引擎Jinjia以及Django的模板语法都非常像。 比如我们在PHP中需要输出变量并且将其进行转义时,语法比较累赘:

复制代码 代码如下:




但是在Twig中可以这样写:

复制代码 代码如下:


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


遍历数组:

复制代码 代码如下:


{% for user in users %}
  * {{ user.name }}
{% else %}
  No user has been found.
{% endfor %}

但是要在Yii Framework集成Twig就会遇到点麻烦了,官方网站中已经有能够集成Twig的方案,所以这里我也不再赘述。但是由于Twig中是不支持PHP语法的,所以在有些表达上会遇到困难,比如我们在写Form的视图时,经常会这么写:

复制代码 代码如下:


beginWidget('CActiveForm'); ?>
    Login
   


     

  •     label($model,'username'); ?>
                    textField($model,'username'); ?>

     

  •  


  •     label($model,'password'); ?>
                    passwordField($model,'password'); ?>

     

  •  


  •    

     


    error($model,'password'); ?>
endWidget(); ?>
但是这样的语法是没法在twig中表达的,所以想去扩展下Twig的功能,让他能够支持我们自定义的widget标签,然后自动解析成我们需要的代码。 总共需要两个类:TokenParser和Node,下面直接上代码:

复制代码 代码如下:


/*
 * 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();');
    }
}
?>


然后在Twig初始化的地方增加我们的语法解析类:

复制代码 代码如下:


$twig->addTokenParser(new Yii_WidgetBlock_TokenParser);


然后我们就可以在twig的模板里这么写了:

复制代码 代码如下:


{% beginwidget 'CActiveForm' as form %}


     

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

  •  

  •     {{ form.label(model, 'password') }}
        {{ form.passwordField(model, 'password') }}
     


{% endwidget %}
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to use Twig with CakePHP? How to use Twig with CakePHP? Jun 05, 2023 pm 07:51 PM

Using Twig in CakePHP is a way to separate templates and views, making the code more modular and maintainable. This article will introduce how to use Twig in CakePHP. 1. Install Twig. First install the Twig library in the project. You can use Composer to complete this task. Run the following command in the console: composerrequire "twig/twig:^2.0" This command will be displayed in the project's vendor

Template library in PHP8.0: Twig Template library in PHP8.0: Twig May 14, 2023 am 08:40 AM

Template library in PHP8.0: TwigTwig is a template library currently widely used in PHP Web applications. It has the characteristics of high readability, easy use and strong scalability. Twig uses simple and easy-to-understand syntax, which can help web developers organize and output HTML, XML, JSON and other text formats in a clear and orderly manner. This article will introduce you to the basic syntax and features of Twig and its use in PHP8.0. The basic syntax of Twig is similar to P

How to use the Twig template engine in PHP for web development How to use the Twig template engine in PHP for web development Jun 25, 2023 pm 04:03 PM

With the continuous development of Web development technology, more and more developers are beginning to look for more flexible and efficient template engines to develop Web applications. Among them, Twig is a very excellent and popular PHP template engine. It is developed based on the Symfony framework and supports unlimited expansion. It is very suitable for building complex web applications. This article will introduce how to use the Twig template engine for web development in PHP. 1. Introduction to Twig template engine Twig is developed by FabienPoten

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

Jump-start WordPress development with Twig and Timber images, menus, and users Jump-start WordPress development with Twig and Timber images, menus, and users Sep 04, 2023 pm 03:37 PM

So far, you have learned the basic concepts of using Twig with Timber while building a modular WordPress theme. We also studied block nesting and multiple inheritance using Twig based on the DRY principle. Today we will explore how to use Twig with the Timber plugin to display attachment images, WordPress menus, and users in your theme. Images in wood Images are one of the important elements of any WordPress theme. In normal WordPress coding practice, images are integrated with PHP within normal HTML image tags. However, Timber provides a fairly comprehensive approach to handling img (image) tags that is modular and clean.

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

See all articles