Volt template engine for Phalcon introductory tutorial

Keywords: PHP Mobile github

The original article was published in: https://www.marser.cn/article/130.html

Volt is an integrated template engine in Phalcon. We can also replace it with other template engines or use multiple template engines at the same time. This article only introduces Phalcon's own volt template engine.

Enabling Volt

Like other template engines, we need to register the volt template into the views component and set the common suffix name of the template file, or use the standardized suffix name. phtml directly to work properly:

//File path: Marser App Frontend FrontendModule. PHP
$di->setShared('view', function () use ($config, $di) {
    $view = new \Phalcon\Mvc\View();
    //Setting the template root directory
    $view->setViewsDir(ROOT_PATH . '/app/frontend/views/');
    //Register Template Engine
    $view->registerEngines(array(
        //Setting the template suffix name
        '.phtml' => function ($view, $di) use ($config) {
            $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
            $volt->setOptions(array(
                //Whether Templates are compiled in real time
                'compileAlways' => false,
                //Template Compilation Directory
                'compiledPath' => ROOT_PATH . '/app/cache/compiled/frontend'
            ));
            return $volt;
        },
    ));
    return $view;
});

usage

Specific usage of basic usage, variables, ** expression **, process control and so on in volt template has been explained in detail in the document, please refer to it directly. Phalcon document
Here we share some of the more consulted usage and trampled pits.

Controller Designation Template

    public function testAction(){
        $this->view->pick('view/test');
    }

Variable value transfer

    //Variables in Controller
    public function test2Action(){
        //setVar: Passing values individually
        $this->view->setVar('test', 'hello world');

        //setVars: associate arrays to pass values to variables
        //$this->view->setVars([
        //    'test' => 'hellow world',
        //]);
        $this->view->pick('view/test2');
    }

For

Phalcon document There are references to how objects and associative arrays are looped in volt templates, but there are no clear examples to illustrate the use of numerical loops. See the following sample code for specific usage:

{% for i in 0..100 %}
  <div>{{i}}</div>
{% endfor %}

Connector

The connector in the volt template is not., nor +, but ~. The code example is as follows:

  {{ url('user/detail?uid='~user['uid']) }}

Template Inheritance

Phalcon document There are very detailed usage of template inheritance. Here I share with you a pit I stepped through in the process of using template inheritance:

<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
        {% endblock %}
    </head>
    <body>
        <div id="content">
          {% block content %}
            <div>
              {% block subContent %}{% endblock %}
            </div>
          {% endblock %}
      </div>
    </body>
</html>

During template compilation, the following error messages are reported:

#block blocks in template inheritance cannot be nested
Embedding blocks into other blocks is not supported

At present, there is no official plan to support this function, so when you use template inheritance, you need to pay special attention to avoid the problem of block nesting.

Extended Template Function

The volt template provides some basic functions in common use. If you want to use custom functions or other functions that come with PHP, you need to register functions into the volt template.
First, we define a volt template base class and add functions through the template compiler:

//File path: Marser App Core PhalBaseVolt. PHP
use \Phalcon\Mvc\View\Engine\Volt;

class PhalBaseVolt extends Volt{

    /**
     * Adding Extension Functions
     */
    public function initFunction(){
        $compiler = $this->getCompiler();

        // Add PHP's own explode function 
        $compiler -> addFunction('explode', 'explode');

        // Add a custom get_userinfo function
        //$resolvedArgs is an arbitrary parameter that can receive multiple parameters
        //It is important to note that the return return value in an anonymous function must be of string type, and the member method must be invoked directly through the scope resolution operator (::) without instantiating the class.
        $compiler -> addFunction('get_userinfo', function($resolvedArgs, $exprArgs) use ($compiler){
            return '\Marser\App\Libs\Test::get_userinfo(' . $resolvedArgs . ')';
        });
    }
}

The code for the custom function get_userinfo() is as follows:

//File path: Marser App Libs Test. PHP
class Test {

    public function get_userinfo($username, $age, $mobile){
        return "User name:{$username}, Age:{$age}, Contact information:{$mobile}";
    }
}

With the above code, PHP's own explode() function and the custom get_userinfo() function in the program have been added to the template compiler.

Then, we modify the views object registered in DI:

        //File path: Marser App Frontend FrontendModule. PHP
        $di -> setShared('view', function() use($config) {
            $view = new \Phalcon\Mvc\View();
            #Setting the template root directory
            $view -> setViewsDir(ROOT_PATH . '/app/frontend/views/');
            #Register Template Engine
            $view -> registerEngines(array(
                #Setting the template suffix name
                '.phtml' => function($view, $di) use($config) {
                    #Instantiate volt template object
                    $volt = new \Marser\App\Core\PhalBaseVolt($view, $di);
                    #Setting Template Configuration Items
                    $volt -> setOptions(array(
                        #Whether Templates are compiled in real time
                        'compileAlways' => false,
                        #Template Compilation Directory
                        'compiledPath'  =>  ROOT_PATH . '/app/cache/compiled/frontend'
                    ));
                    # Be careful! The difference is in this line - - add template extension functions
                    $volt -> initFunction();
                    return $volt;
                },
            ));
            return $view;
        });

So far, the explode() and get_userinfo() functions have been registered in the template. So, how to call it?
explode() calls the sample code in the template:

{% set introArray = explode('-', intro) %}
{% for value in introArray %}
  <div>{{value}}</div>
{% endfor %}

The sample code that the custom function get_userinfo() calls in the template:

  {{get_userinfo('admin', '20', 'Shanghai China')}}

Whether it's a PHP self-contained function or a custom function in the program, it's only necessary to pass parameters in the order of parameters when the function is defined.

The above code is hosted in github: https://github.com/KevinJay/marser-phalcon-demo

Finally, welcome to join QQ group exchange discussion:

  • Guangzhou PHP High-end Exchange Group: 158587573
  • Phalcon Player Cluster: 150237524

Posted by greggustin on Wed, 03 Jul 2019 14:28:16 -0700