Home Backend Development PHP Tutorial Example of using PHP template engine Twig in Yii framework_PHP tutorial

Example of using PHP template engine Twig in Yii framework_PHP tutorial

Jul 13, 2016 am 10:28 AM
twig yii

Twig is a fast, safe, and flexible PHP template engine. It has many built-in filters and tags, and supports template inheritance, allowing you to use the most concise code to describe your template. Its syntax is very similar to the template engine Jinjia under Python and the template syntax of Django. For example, when we need to output variables and escape them in PHP, the syntax is cumbersome:

Copy code The code is as follows:



But in Twig you can write like this:
Copy code The code is as follows:

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

Traverse the array:
Copy code The code is as follows:

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

But it will be a bit troublesome to integrate Twig in Yii Framework. The official website already has a solution to integrate Twig, so I won’t go into details here. However, since Twig does not support PHP syntax, we will encounter difficulties in some expressions. For example, when we write the view of the Form, we often write like this:

Copy code The code is as follows:

beginWidget('CActiveForm'); ?>
Login                                                                                                        form->textField($model,'username'); ?>


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

    ,'password'); ?>




  • error($model,'password'); ?>

    endWidget(); ?>


    But such syntax cannot be expressed in twig, so I want to extend the function of Twig so that it can support our customized widget tags and then automatically parse it into the code we need. . A total of two classes are needed: TokenParser and Node. The code is directly below:



    Copy the code
    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->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();');
        }
    }
    ?>


    Then add our syntax parsing class where Twig is initialized:
    Copy the code The code is as follows:

    $twig ->addTokenParser(new Yii_WidgetBlock_TokenParser);

    Then we can write this in the twig template:
    Copy the code 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 %}

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/802218.htmlTechArticleTwig is a fast, safe and flexible PHP template engine. It has many built-in filters and tags and supports Template inheritance allows you to use the most concise code to describe your template. His language...
    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    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)

    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

    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

    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

    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.

    Advanced Skinning in PHP: How to Use Twig Advanced Skinning in PHP: How to Use Twig Jun 19, 2023 pm 04:03 PM

    In web development, page presentation is crucial. For PHP developers, when developing a dynamic website, it is easy to get stuck in a large number of HTML tags and PHP code. Once the style or layout needs to be modified, the code must be modified over and over again, which is extremely costly to maintain. To solve this problem, modern PHP frameworks usually provide a template engine. Among them, Twig is one of the more popular template engines. In this article we will cover how and why to use Twig for PHP

    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.

    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

    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

    See all articles