Volt: Template Engine

Volt is an ultra-fast and designer friendly templating language written in C for PHP. It provides you a set of helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, just as you can use it as a stand-alone component in your applications.

Volt - 图1

Volt is inspired by Jinja, originally created by Armin Ronacher. Therefore many developers will be in familiar territory using the same syntax they have been using with similar template engines. Volt’s syntax and features have been enhanced with more elements and of course with the performance that developers have been accustomed to while working with Phalcon.

Introduction

Volt views are compiled to pure PHP code, so basically they save the effort of writing PHP code manually:

  1. {# app/views/products/show.volt #}
  2. {% block last_products %}
  3. {% for product in products %}
  4. * Name: {{ product.name|e }}
  5. {% if product.status === 'Active' %}
  6. Price: {{ product.price + product.taxes/100 }}
  7. {% endif %}
  8. {% endfor %}
  9. {% endblock %}

Activating Volt

As with other templating engines, you may register Volt in the view component, using a new extension or reusing the standard .phtml:

  1. <?php
  2. use Phalcon\Mvc\View;
  3. use Phalcon\Mvc\View\Engine\Volt;
  4. // Register Volt as a service
  5. $di->set(
  6. 'voltService',
  7. function ($view, $di) {
  8. $volt = new Volt($view, $di);
  9. $volt->setOptions(
  10. [
  11. 'compiledPath' => '../app/compiled-templates/',
  12. 'compiledExtension' => '.compiled',
  13. ]
  14. );
  15. return $volt;
  16. }
  17. );
  18. // Register Volt as template engine
  19. $di->set(
  20. 'view',
  21. function () {
  22. $view = new View();
  23. $view->setViewsDir('../app/views/');
  24. $view->registerEngines(
  25. [
  26. '.volt' => 'voltService',
  27. ]
  28. );
  29. return $view;
  30. }
  31. );

Use the standard .phtml extension:

  1. <?php
  2. $view->registerEngines(
  3. [
  4. '.phtml' => 'voltService',
  5. ]
  6. );

You don’t have to specify the Volt Service in the DI; you can also use the Volt engine with the default settings:

  1. <?php
  2. $view->registerEngines(
  3. [
  4. '.volt' => Phalcon\Mvc\View\Engine\Volt::class,
  5. ]
  6. );

`If you do not want to reuse Volt as a service, you can pass an anonymous function to register the engine instead of a service name:

  1. <?php
  2. use Phalcon\Mvc\View;
  3. use Phalcon\Mvc\View\Engine\Volt;
  4. // Register Volt as template engine with an anonymous function
  5. $di->set(
  6. 'view',
  7. function () {
  8. $view = new View();
  9. $view->setViewsDir('../app/views/');
  10. $view->registerEngines(
  11. [
  12. '.volt' => function ($view, $di) {
  13. $volt = new Volt($view, $di);
  14. // Set some options here
  15. return $volt;
  16. }
  17. ]
  18. );
  19. return $view;
  20. }
  21. );

The following options are available in Volt:

OptionDescriptionDefault
autoescapeEnables globally autoescape of HTMLfalse
compileAlwaysTell Volt if the templates must be compiled in each request or only when they changefalse
compiledExtensionAn additional extension appended to the compiled PHP file.php
compiledPathA writable path where the compiled PHP templates will be placed./
compiledSeparatorVolt replaces the directory separators / and \ by this separator in order to create a single file in the compiled directory%%
prefixAllows to prepend a prefix to the templates in the compilation pathnull
statWhether Phalcon must check if exists differences between the template file and its compiled pathtrue

The compilation path is generated according to the above options, if the developer wants total freedom defining the compilation path, an anonymous function can be used to generate it, this function receives the relative path to the template in the views directory. The following examples show how to change the compilation path dynamically:

  1. <?php
  2. // Just append the .php extension to the template path
  3. // leaving the compiled templates in the same directory
  4. $volt->setOptions(
  5. [
  6. 'compiledPath' => function ($templatePath) {
  7. return $templatePath . '.php';
  8. }
  9. ]
  10. );
  11. // Recursively create the same structure in another directory
  12. $volt->setOptions(
  13. [
  14. 'compiledPath' => function ($templatePath) {
  15. $dirName = dirname($templatePath);
  16. if (!is_dir('cache/' . $dirName)) {
  17. mkdir('cache/' . $dirName , 0777 , true);
  18. }
  19. return 'cache/' . $dirName . '/'. $templatePath . '.php';
  20. }
  21. ]
  22. );

Basic Usage

A view consists of Volt code, PHP and HTML. A set of special delimiters is available to enter into Volt mode. {% … %} is used to execute statements such as for-loops or assign values and {{ … }},prints the result of an expression to the template.

Below is a minimal template that illustrates a few basics:

  1. {# app/views/posts/show.phtml #}
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>{{ title }} - An example blog</title>
  6. </head>
  7. <body>
  8. {% if show_navigation %}
  9. <ul id='navigation'>
  10. {% for item in menu %}
  11. <li>
  12. <a href='{{ item.href }}'>
  13. {{ item.caption }}
  14. </a>
  15. </li>
  16. {% endfor %}
  17. </ul>
  18. {% endif %}
  19. <h1>{{ post.title }}</h1>
  20. <div class='content'>
  21. {{ post.content }}
  22. </div>
  23. </body>
  24. </html>

Using Phalcon\Mvc\View you can pass variables from the controller to the views. In the above example, four variables were passed to the view: show_navigation, menu, title and post:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function showAction()
  6. {
  7. $post = Post::findFirst();
  8. $menu = Menu::findFirst();
  9. $this->view->show_navigation = true;
  10. $this->view->menu = $menu;
  11. $this->view->title = $post->title;
  12. $this->view->post = $post;
  13. // Or...
  14. $this->view->setVar('show_navigation', true);
  15. $this->view->setVar('menu', $menu);
  16. $this->view->setVar('title', $post->title);
  17. $this->view->setVar('post', $post);
  18. }
  19. }

Variables

Object variables may have attributes which can be accessed using the syntax: foo.bar. If you are passing arrays, you have to use the square bracket syntax: foo['bar']

  1. {{ post.title }} {# for $post->title #}
  2. {{ post['title'] }} {# for $post['title'] #}

Filters

Variables can be formatted or modified using filters. The pipe operator | is used to apply filters to variables:

  1. {{ post.title|e }}
  2. {{ post.content|striptags }}
  3. {{ name|capitalize|trim }}

The following is the list of available built-in filters in Volt:

FilterDescription
absApplies the abs PHP function to a value.
capitalizeCapitalizes a string by applying the ucwords PHP function to the value
convert_encodingConverts a string from one charset to another
defaultSets a default value in case that the evaluated expression is empty (is not set or evaluates to a falsy value)
eApplies Phalcon\Escaper->escapeHtml() to the value
escapeApplies Phalcon\Escaper->escapeHtml() to the value
escape_attrApplies Phalcon\Escaper->escapeHtmlAttr() to the value
escape_cssApplies Phalcon\Escaper->escapeCss() to the value
escape_jsApplies Phalcon\Escaper->escapeJs() to the value
formatFormats a string using sprintf.
json_encodeConverts a value into its JSON representation
json_decodeConverts a value from its JSON representation to a PHP representation
joinJoins the array parts using a separator join
keysReturns the array keys using array_keys
left_trimApplies the ltrim PHP function to the value. Removing extra spaces
lengthCounts the string length or how many items are in an array or object
lowerChange the case of a string to lowercase
nl2brChanges newlines \n by line breaks (<br />). Uses the PHP function nl2br
right_trimApplies the rtrim PHP function to the value. Removing extra spaces
sortSorts an array using the PHP function asort
stripslashesApplies the stripslashes PHP function to the value. Removing escaped quotes
striptagsApplies the striptags PHP function to the value. Removing HTML tags
trimApplies the trim PHP function to the value. Removing extra spaces
upperChange the case of a string to uppercase
url_encodeApplies the urlencode PHP function to the value

Examples:

  1. {# e or escape filter #}
  2. {{ '<h1>Hello<h1>'|e }}
  3. {{ '<h1>Hello<h1>'|escape }}
  4. {# trim filter #}
  5. {{ ' hello '|trim }}
  6. {# striptags filter #}
  7. {{ '<h1>Hello<h1>'|striptags }}
  8. {# slashes filter #}
  9. {{ ''this is a string''|slashes }}
  10. {# stripslashes filter #}
  11. {{ '\'this is a string\''|stripslashes }}
  12. {# capitalize filter #}
  13. {{ 'hello'|capitalize }}
  14. {# lower filter #}
  15. {{ 'HELLO'|lower }}
  16. {# upper filter #}
  17. {{ 'hello'|upper }}
  18. {# length filter #}
  19. {{ 'robots'|length }}
  20. {{ [1, 2, 3]|length }}
  21. {# nl2br filter #}
  22. {{ 'some\ntext'|nl2br }}
  23. {# sort filter #}
  24. {% set sorted = [3, 1, 2]|sort %}
  25. {# keys filter #}
  26. {% set keys = ['first': 1, 'second': 2, 'third': 3]|keys %}
  27. {# join filter #}
  28. {% set joined = 'a'..'z'|join(',') %}
  29. {# format filter #}
  30. {{ 'My real name is %s'|format(name) }}
  31. {# json_encode filter #}
  32. {% set encoded = robots|json_encode %}
  33. {# json_decode filter #}
  34. {% set decoded = '{'one':1,'two':2,'three':3}'|json_decode %}
  35. {# url_encode filter #}
  36. {{ post.permanent_link|url_encode }}
  37. {# convert_encoding filter #}
  38. {{ 'désolé'|convert_encoding('utf8', 'latin1') }}

Comments

Comments may also be added to a template using the {# … #} delimiters. All text inside them is just ignored in the final output:

  1. {# note: this is a comment
  2. {% set price = 100; %}
  3. #}

List of Control Structures

Volt provides a set of basic but powerful control structures for use in templates:

For

Loop over each item in a sequence. The following example shows how to traverse a set of ‘robots’ and print his/her name:

  1. <h1>Robots</h1>
  2. <ul>
  3. {% for robot in robots %}
  4. <li>
  5. {{ robot.name|e }}
  6. </li>
  7. {% endfor %}
  8. </ul>

for-loops can also be nested:

  1. <h1>Robots</h1>
  2. {% for robot in robots %}
  3. {% for part in robot.parts %}
  4. Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
  5. {% endfor %}
  6. {% endfor %}

You can get the element keys as in the PHP counterpart using the following syntax:

  1. {% set numbers = ['one': 1, 'two': 2, 'three': 3] %}
  2. {% for name, value in numbers %}
  3. Name: {{ name }} Value: {{ value }}
  4. {% endfor %}

An if evaluation can be optionally set:

  1. {% set numbers = ['one': 1, 'two': 2, 'three': 3] %}
  2. {% for value in numbers if value < 2 %}
  3. Value: {{ value }}
  4. {% endfor %}
  5. {% for name, value in numbers if name !== 'two' %}
  6. Name: {{ name }} Value: {{ value }}
  7. {% endfor %}

If an else is defined inside the for, it will be executed if the expression in the iterator result in zero iterations:

  1. <h1>Robots</h1>
  2. {% for robot in robots %}
  3. Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
  4. {% else %}
  5. There are no robots to show
  6. {% endfor %}

Alternative syntax:

  1. <h1>Robots</h1>
  2. {% for robot in robots %}
  3. Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
  4. {% elsefor %}
  5. There are no robots to show
  6. {% endfor %}

Loop Controls

The break and continue statements can be used to exit from a loop or force an iteration in the current block:

  1. {# skip the even robots #}
  2. {% for index, robot in robots %}
  3. {% if index is even %}
  4. {% continue %}
  5. {% endif %}
  6. ...
  7. {% endfor %}
  1. {# exit the foreach on the first even robot #}
  2. {% for index, robot in robots %}
  3. {% if index is even %}
  4. {% break %}
  5. {% endif %}
  6. ...
  7. {% endfor %}

If

As PHP, an if statement checks if an expression is evaluated as true or false:

  1. <h1>Cyborg Robots</h1>
  2. <ul>
  3. {% for robot in robots %}
  4. {% if robot.type === 'cyborg' %}
  5. <li>{{ robot.name|e }}</li>
  6. {% endif %}
  7. {% endfor %}
  8. </ul>

The else clause is also supported:

  1. <h1>Robots</h1>
  2. <ul>
  3. {% for robot in robots %}
  4. {% if robot.type === 'cyborg' %}
  5. <li>{{ robot.name|e }}</li>
  6. {% else %}
  7. <li>{{ robot.name|e }} (not a cyborg)</li>
  8. {% endif %}
  9. {% endfor %}
  10. </ul>

The elseif control flow structure can be used together with if to emulate a switch block:

  1. {% if robot.type === 'cyborg' %}
  2. Robot is a cyborg
  3. {% elseif robot.type === 'virtual' %}
  4. Robot is virtual
  5. {% elseif robot.type === 'mechanical' %}
  6. Robot is mechanical
  7. {% endif %}

Switch

An alternative to the if statement is switch, allowing you to create logical execution paths in your application:

  1. {% switch foo %}
  2. {% case 0 %}
  3. {% case 1 %}
  4. {% case 2 %}
  5. "foo" is less than 3 but not negative
  6. {% break %}
  7. {% case 3 %}
  8. "foo" is 3
  9. {% break %}
  10. {% default %}
  11. "foo" is {{ foo }}
  12. {% endswitch %}

The switch statement executes statement by statement, therefore the break statement is necessary in some cases. Any output (including whitespace) between a switch statement and the first case will result in a syntax error. Empty lines and whitespaces can therefore be cleared to reduce the number of errors see here.

case without switch

  1. {% case EXPRESSION %}

Will throw Fatal error: Uncaught Phalcon\Mvc\View\Exception: Unexpected CASE.

switch without endswitch

  1. {% switch EXPRESSION %}
  2. Will throw `Fatal error: Uncaught Phalcon\Mvc\View\Exception: Syntax error, unexpected EOF in ..., there is a 'switch' block without 'endswitch'`.

default without switch

  1. {% default %}

Will not throw an error because default is a reserved word for filters like {{ EXPRESSION | default(VALUE) }} but in this case the expression will only output an empty char ‘’ .

nested switch

  1. {% switch EXPRESSION %}
  2. {% switch EXPRESSION %}
  3. {% endswitch %}
  4. {% endswitch %}

Will throw Fatal error: Uncaught Phalcon\Mvc\View\Exception: A nested switch detected. There is no nested switch-case statements support in … on line …

a switch without an expression

  1. {% switch %}
  2. {% case EXPRESSION %}
  3. {% break %}
  4. {% endswitch %}

Will throw Fatal error: Uncaught Phalcon\Mvc\View\Exception: Syntax error, unexpected token %} in … on line …

Loop Context

A special variable is available inside for loops providing you information about

VariableDescription
loop.indexThe current iteration of the loop. (1 indexed)
loop.index0The current iteration of the loop. (0 indexed)
loop.revindexThe number of iterations from the end of the loop (1 indexed)
loop.revindex0The number of iterations from the end of the loop (0 indexed)
loop.firstTrue if in the first iteration.
loop.lastTrue if in the last iteration.
loop.lengthThe number of items to iterate

Example:

  1. {% for robot in robots %}
  2. {% if loop.first %}
  3. <table>
  4. <tr>
  5. <th>#</th>
  6. <th>Id</th>
  7. <th>Name</th>
  8. </tr>
  9. {% endif %}
  10. <tr>
  11. <td>{{ loop.index }}</td>
  12. <td>{{ robot.id }}</td>
  13. <td>{{ robot.name }}</td>
  14. </tr>
  15. {% if loop.last %}
  16. </table>
  17. {% endif %}
  18. {% endfor %}

Assignments

Variables may be changed in a template using the instruction set:

  1. {% set fruits = ['Apple', 'Banana', 'Orange'] %}
  2. {% set name = robot.name %}

Multiple assignments are allowed in the same instruction:

  1. {% set fruits = ['Apple', 'Banana', 'Orange'], name = robot.name, active = true %}

Additionally, you can use compound assignment operators:

  1. {% set price += 100.00 %}
  2. {% set age *= 5 %}

The following operators are available:

OperatorDescription
=Standard Assignment
+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment

Expressions

Volt provides a basic set of expression support, including literals and common operators. A expression can be evaluated and printed using the {{ and }} delimiters:

  1. {{ (1 + 1) * 2 }}

If an expression needs to be evaluated without be printed the do statement can be used:

  1. {% do (1 + 1) * 2 %}

Literals

The following literals are supported:

FilterDescription
'this is a string'Text between double quotes or single quotes are handled as strings
100.25Numbers with a decimal part are handled as doubles/floats
100Numbers without a decimal part are handled as integers
falseConstant ‘false’ is the boolean false value
trueConstant ‘true’ is the boolean true value
nullConstant ‘null’ is the Null value

Arrays

Whether you’re using PHP 5.3 or >= 5.4 you can create arrays by enclosing a list of values in square brackets:

  1. {# Simple array #}
  2. {{ ['Apple', 'Banana', 'Orange'] }}
  3. {# Other simple array #}
  4. {{ ['Apple', 1, 2.5, false, null] }}
  5. {# Multi-Dimensional array #}
  6. {{ [[1, 2], [3, 4], [5, 6]] }}
  7. {# Hash-style array #}
  8. {{ ['first': 1, 'second': 4/2, 'third': '3'] }}

Curly braces also can be used to define arrays or hashes:

  1. {% set myArray = {'Apple', 'Banana', 'Orange'} %}
  2. {% set myHash = {'first': 1, 'second': 4/2, 'third': '3'} %}

Math

You may make calculations in templates using the following operators:

OperatorDescription
+Perform an adding operation. {{ 2 + 3 }} returns 5
-Perform a substraction operation {{ 2 - 3 }} returns -1
Perform a multiplication operation {{ 2 3 }} returns 6
/Perform a division operation {{ 10 / 2 }} returns 5
%Calculate the remainder of an integer division {{ 10 % 3 }} returns 1

Comparisons

The following comparison operators are available:

OperatorDescription
==Check whether both operands are equal
!=Check whether both operands aren’t equal
<>Check whether both operands aren’t equal
>Check whether left operand is greater than right operand
<Check whether left operand is less than right operand
<=Check whether left operand is less or equal than right operand
>=Check whether left operand is greater or equal than right operand
===Check whether both operands are identical
!==Check whether both operands aren’t identical

Logic

Logic operators are useful in the if expression evaluation to combine multiple tests:

OperatorDescription
orReturn true if the left or right operand is evaluated as true
andReturn true if both left and right operands are evaluated as true
notNegates an expression
( expr )Parenthesis groups expressions

Other Operators

Additional operators seen the following operators are available:

OperatorDescription
~Concatenates both operands {{ 'hello ' ~ 'world' }}
|Applies a filter in the right operand to the left {{ 'hello'|uppercase }}
..Creates a range {{ 'a'..'z' }} {{ 1..10 }}
isSame as == (equals), also performs tests
inTo check if an expression is contained into other expressions if 'a' in 'abc'
is notSame as != (not equals)
'a' ? 'b' : 'c'Ternary operator. The same as the PHP ternary operator
++Increments a value
Decrements a value

The following example shows how to use operators:

  1. {% set robots = ['Voltron', 'Astro Boy', 'Terminator', 'C3PO'] %}
  2. {% for index in 0..robots|length %}
  3. {% if robots[index] is defined %}
  4. {{ 'Name: ' ~ robots[index] }}
  5. {% endif %}
  6. {% endfor %}

Tests

Tests can be used to test if a variable has a valid expected value. The operator is is used to perform the tests:

  1. {% set robots = ['1': 'Voltron', '2': 'Astro Boy', '3': 'Terminator', '4': 'C3PO'] %}
  2. {% for position, name in robots %}
  3. {% if position is odd %}
  4. {{ name }}
  5. {% endif %}
  6. {% endfor %}

The following built-in tests are available in Volt:

TestDescription
definedChecks if a variable is defined (isset())
divisiblebyChecks if a value is divisible by other value
emptyChecks if a variable is empty
evenChecks if a numeric value is even
iterableChecks if a value is iterable. Can be traversed by a ‘for’ statement
numericChecks if value is numeric
oddChecks if a numeric value is odd
sameasChecks if a value is identical to other value
scalarChecks if value is scalar (not an array or object)
typeChecks if a value is of the specified type

More examples:

  1. {% if robot is defined %}
  2. The robot variable is defined
  3. {% endif %}
  4. {% if robot is empty %}
  5. The robot is null or isn't defined
  6. {% endif %}
  7. {% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 3: 'Bender'] %}
  8. {% if key is even %}
  9. {{ name }}
  10. {% endif %}
  11. {% endfor %}
  12. {% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 3: 'Bender'] %}
  13. {% if key is odd %}
  14. {{ name }}
  15. {% endif %}
  16. {% endfor %}
  17. {% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 'third': 'Bender'] %}
  18. {% if key is numeric %}
  19. {{ name }}
  20. {% endif %}
  21. {% endfor %}
  22. {% set robots = [1: 'Voltron', 2: 'Astroy Boy'] %}
  23. {% if robots is iterable %}
  24. {% for robot in robots %}
  25. ...
  26. {% endfor %}
  27. {% endif %}
  28. {% set world = 'hello' %}
  29. {% if world is sameas('hello') %}
  30. {{ 'it's hello' }}
  31. {% endif %}
  32. {% set external = false %}
  33. {% if external is type('boolean') %}
  34. {{ 'external is false or true' }}
  35. {% endif %}

Macros

Macros can be used to reuse logic in a template, they act as PHP functions, can receive parameters and return values:

  1. {# Macro 'display a list of links to related topics' #}
  2. {%- macro related_bar(related_links) %}
  3. <ul>
  4. {%- for link in related_links %}
  5. <li>
  6. <a href='{{ url(link.url) }}' title='{{ link.title|striptags }}'>
  7. {{ link.text }}
  8. </a>
  9. </li>
  10. {%- endfor %}
  11. </ul>
  12. {%- endmacro %}
  13. {# Print related links #}
  14. {{ related_bar(links) }}
  15. <div>This is the content</div>
  16. {# Print related links again #}
  17. {{ related_bar(links) }}

When calling macros, parameters can be passed by name:

  1. {%- macro error_messages(message, field, type) %}
  2. <div>
  3. <span class='error-type'>{{ type }}</span>
  4. <span class='error-field'>{{ field }}</span>
  5. <span class='error-message'>{{ message }}</span>
  6. </div>
  7. {%- endmacro %}
  8. {# Call the macro #}
  9. {{ error_messages('type': 'Invalid', 'message': 'The name is invalid', 'field': 'name') }}

Macros can return values:

  1. {%- macro my_input(name, class) %}
  2. {% return text_field(name, 'class': class) %}
  3. {%- endmacro %}
  4. {# Call the macro #}
  5. {{ '<p>' ~ my_input('name', 'input-text') ~ '</p>' }}

And receive optional parameters:

  1. {%- macro my_input(name, class='input-text') %}
  2. {% return text_field(name, 'class': class) %}
  3. {%- endmacro %}
  4. {# Call the macro #}
  5. {{ '<p>' ~ my_input('name') ~ '</p>' }}
  6. {{ '<p>' ~ my_input('name', 'input-text') ~ '</p>' }}

Using Tag Helpers

Volt is highly integrated with Phalcon\Tag, so it’s easy to use the helpers provided by that component in a Volt template:

  1. {{ javascript_include('js/jquery.js') }}
  2. {{ form('products/save', 'method': 'post') }}
  3. <label for='name'>Name</label>
  4. {{ text_field('name', 'size': 32) }}
  5. <label for='type'>Type</label>
  6. {{ select('type', productTypes, 'using': ['id', 'name']) }}
  7. {{ submit_button('Send') }}
  8. {{ end_form() }}

The following PHP is generated:

  1. <?php echo Phalcon\Tag::javascriptInclude('js/jquery.js') ?>
  2. <?php echo Phalcon\Tag::form(array('products/save', 'method' => 'post')); ?>
  3. <label for='name'>Name</label>
  4. <?php echo Phalcon\Tag::textField(array('name', 'size' => 32)); ?>
  5. <label for='type'>Type</label>
  6. <?php echo Phalcon\Tag::select(array('type', $productTypes, 'using' => array('id', 'name'))); ?>
  7. <?php echo Phalcon\Tag::submitButton('Send'); ?>
  8. {{ end_form() }}

To call a Phalcon\Tag helper, you only need to call an uncamelized version of the method:

MethodVolt function
Phalcon\Tag::checkFieldcheck_field
Phalcon\Tag::dateFielddate_field
Phalcon\Tag::emailFieldemail_field
Phalcon\Tag::endFormend_form
Phalcon\Tag::fileFieldfile_field
Phalcon\Tag::formform
Phalcon\Tag::friendlyTitlefriendly_title
Phalcon\Tag::getTitleget_title
Phalcon\Tag::hiddenFieldhidden_field
Phalcon\Tag::imageimage
Phalcon\Tag::javascriptIncludejavascript_include
Phalcon\Tag::linkTolink_to
Phalcon\Tag::numericFieldnumeric_field
Phalcon\Tag::passwordFieldpassword_field
Phalcon\Tag::radioFieldradio_field
Phalcon\Tag::selectselect
Phalcon\Tag::selectStaticselect_static
Phalcon\Tag::stylesheetLinkstylesheet_link
Phalcon\Tag::submitButtonsubmit_button
Phalcon\Tag::textAreatext_area
Phalcon\Tag::textFieldtext_field

Functions

The following built-in functions are available in Volt:

NameDescription
contentIncludes the content produced in a previous rendering stage
get_contentSame as content
partialDynamically loads a partial view in the current template
superRender the contents of the parent block
timeCalls the PHP function with the same name
dateCalls the PHP function with the same name
dumpCalls the PHP function var_dump()
versionReturns the current version of the framework
constantReads a PHP constant
urlGenerate a URL using the ‘url’ service

View Integration

Also, Volt is integrated with Phalcon\Mvc\View, you can play with the view hierarchy and include partials as well:

  1. {{ content() }}
  2. <!-- Simple include of a partial -->
  3. <div id='footer'>{{ partial('partials/footer') }}</div>
  4. <!-- Passing extra variables -->
  5. <div id='footer'>{{ partial('partials/footer', ['links': links]) }}</div>

A partial is included in runtime, Volt also provides include, this compiles the content of a view and returns its contents as part of the view which was included:

  1. {# Simple include of a partial #}
  2. <div id='footer'>
  3. {% include 'partials/footer' %}
  4. </div>
  5. {# Passing extra variables #}
  6. <div id='footer'>
  7. {% include 'partials/footer' with ['links': links] %}
  8. </div>

Include

include has a special behavior that will help us improve performance a bit when using Volt, if you specify the extension when including the file and it exists when the template is compiled, Volt can inline the contents of the template in the parent template where it’s included. Templates aren’t inlined if the include have variables passed with with:

  1. {# The contents of 'partials/footer.volt' is compiled and inlined #}
  2. <div id='footer'>
  3. {% include 'partials/footer.volt' %}
  4. </div>

Partial vs Include

Keep the following points in mind when choosing to use the partial function or include:

TypeDescription
partialallows you to include templates made in Volt and in other template engines as well
allows you to pass an expression like a variable allowing to include the content of other view dynamically
is better if the content that you have to include changes frequently
includescopies the compiled content into the view which improves the performance
only allows to include templates made with Volt
requires an existing template at compile time

Template Inheritance

With template inheritance you can create base templates that can be extended by others templates allowing to reuse code. A base template define blocks than can be overridden by a child template. Let’s pretend that we have the following base template:

  1. {# templates/base.volt #}
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. {% block head %}
  6. <link rel='stylesheet' href='style.css' />
  7. {% endblock %}
  8. <title>{% block title %}{% endblock %} - My Webpage</title>
  9. </head>
  10. <body>
  11. <div id='content'>{% block content %}{% endblock %}</div>
  12. <div id='footer'>
  13. {% block footer %}&copy; Copyright 2015, All rights reserved.{% endblock %}
  14. </div>
  15. </body>
  16. </html>

From other template we could extend the base template replacing the blocks:

  1. {% extends 'templates/base.volt' %}
  2. {% block title %}Index{% endblock %}
  3. {% block head %}<style type='text/css'>.important { color: #336699; }</style>{% endblock %}
  4. {% block content %}
  5. <h1>Index</h1>
  6. <p class='important'>Welcome on my awesome homepage.</p>
  7. {% endblock %}

Not all blocks must be replaced at a child template, only those that are needed. The final output produced will be the following:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style type='text/css'>.important { color: #336699; }</style>
  5. <title>Index - My Webpage</title>
  6. </head>
  7. <body>
  8. <div id='content'>
  9. <h1>Index</h1>
  10. <p class='important'>Welcome on my awesome homepage.</p>
  11. </div>
  12. <div id='footer'>
  13. &copy; Copyright 2015, All rights reserved.
  14. </div>
  15. </body>
  16. </html>

Multiple Inheritance

Extended templates can extend other templates. The following example illustrates this:

  1. {# main.volt #}
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. {% block content %}{% endblock %}
  9. </body>
  10. </html>

Template layout.volt extends main.volt

  1. {# layout.volt #}
  2. {% extends 'main.volt' %}
  3. {% block content %}
  4. <h1>Table of contents</h1>
  5. {% endblock %}

Finally a view that extends layout.volt:

  1. {# index.volt #}
  2. {% extends 'layout.volt' %}
  3. {% block content %}
  4. {{ super() }}
  5. <ul>
  6. <li>Some option</li>
  7. <li>Some other option</li>
  8. </ul>
  9. {% endblock %}

Rendering index.volt produces:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Title</title>
  5. </head>
  6. <body>
  7. <h1>Table of contents</h1>
  8. <ul>
  9. <li>Some option</li>
  10. <li>Some other option</li>
  11. </ul>
  12. </body>
  13. </html>

Note the call to the function super(). With that function it’s possible to render the contents of the parent block. As partials, the path set to extends is a relative path under the current views directory (i.e. app/views/).

Autoescape mode

You can enable auto-escaping of all variables printed in a block using the autoescape mode:

  1. Manually escaped: {{ robot.name|e }}
  2. {% autoescape true %}
  3. Autoescaped: {{ robot.name }}
  4. {% autoescape false %}
  5. No Autoescaped: {{ robot.name }}
  6. {% endautoescape %}
  7. {% endautoescape %}

Extending Volt

Unlike other template engines, Volt itself is not required to run the compiled templates. Once the templates are compiled there is no dependence on Volt. With performance independence in mind, Volt only acts as a compiler for PHP templates.

The Volt compiler allow you to extend it adding more functions, tests or filters to the existing ones.

Functions

Functions act as normal PHP functions, a valid string name is required as function name. Functions can be added using two strategies, returning a simple string or using an anonymous function. Always is required that the chosen strategy returns a valid PHP string expression:

  1. <?php
  2. use Phalcon\Mvc\View\Engine\Volt;
  3. $volt = new Volt($view, $di);
  4. $compiler = $volt->getCompiler();
  5. // This binds the function name 'shuffle' in Volt to the PHP function 'str_shuffle'
  6. $compiler->addFunction('shuffle', 'str_shuffle');

Register the function with an anonymous function. This case we use $resolvedArgs to pass the arguments exactly as were passed in the arguments:

  1. <?php
  2. $compiler->addFunction(
  3. 'widget',
  4. function ($resolvedArgs, $exprArgs) {
  5. return 'MyLibrary\Widgets::get(' . $resolvedArgs . ')';
  6. }
  7. );

Treat the arguments independently and unresolved:

  1. <?php
  2. $compiler->addFunction(
  3. 'repeat',
  4. function ($resolvedArgs, $exprArgs) use ($compiler) {
  5. // Resolve the first argument
  6. $firstArgument = $compiler->expression($exprArgs[0]['expr']);
  7. // Checks if the second argument was passed
  8. if (isset($exprArgs[1])) {
  9. $secondArgument = $compiler->expression($exprArgs[1]['expr']);
  10. } else {
  11. // Use '10' as default
  12. $secondArgument = '10';
  13. }
  14. return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
  15. }
  16. );

Generate the code based on some function availability:

  1. <?php
  2. $compiler->addFunction(
  3. 'contains_text',
  4. function ($resolvedArgs, $exprArgs) {
  5. if (function_exists('mb_stripos')) {
  6. return 'mb_stripos(' . $resolvedArgs . ')';
  7. } else {
  8. return 'stripos(' . $resolvedArgs . ')';
  9. }
  10. }
  11. );

Built-in functions can be overridden adding a function with its name:

  1. <?php
  2. // Replace built-in function dump
  3. $compiler->addFunction('dump', 'print_r');

Filters

A filter has the following form in a template: leftExpr|name(optional-args). Adding new filters is similar as seen with the functions:

  1. <?php
  2. // This creates a filter 'hash' that uses the PHP function 'md5'
  3. $compiler->addFilter('hash', 'md5');
  1. <?php
  2. $compiler->addFilter(
  3. 'int',
  4. function ($resolvedArgs, $exprArgs) {
  5. return 'intval(' . $resolvedArgs . ')';
  6. }
  7. );

Built-in filters can be overridden adding a function with its name:

  1. <?php
  2. // Replace built-in filter 'capitalize'
  3. $compiler->addFilter('capitalize', 'lcfirst');

Extensions

With extensions the developer has more flexibility to extend the template engine, and override the compilation of a specific instruction, change the behavior of an expression or operator, add functions/filters, and more.

An extension is a class that implements the events triggered by Volt as a method of itself. For example, the class below allows to use any PHP function in Volt:

  1. <?php
  2. class PhpFunctionExtension
  3. {
  4. /**
  5. * This method is called on any attempt to compile a function call
  6. */
  7. public function compileFunction($name, $arguments)
  8. {
  9. if (function_exists($name)) {
  10. return $name . '('. $arguments . ')';
  11. }
  12. }
  13. }

The above class implements the method compileFunction which is invoked before any attempt to compile a function call in any template. The purpose of the extension is to verify if a function to be compiled is a PHP function allowing to call it from the template. Events in extensions must return valid PHP code, this will be used as result of the compilation instead of the one generated by Volt. If an event doesn’t return an string the compilation is done using the default behavior provided by the engine.

The following compilation events are available to be implemented in extensions:

Event/MethodDescription
compileFunctionTriggered before trying to compile any function call in a template
compileFilterTriggered before trying to compile any filter call in a template
resolveExpressionTriggered before trying to compile any expression. This allows the developer to override operators
compileStatementTriggered before trying to compile any expression. This allows the developer to override any statement

Volt extensions must be in registered in the compiler making them available in compile time:

  1. <?php
  2. // Register the extension in the compiler
  3. $compiler->addExtension(
  4. new PhpFunctionExtension()
  5. );

Caching view fragments

With Volt it’s easy cache view fragments. This caching improves performance preventing that the contents of a block from being executed by PHP each time the view is displayed:

  1. {% cache 'sidebar' %}
  2. <!-- generate this content is slow so we are going to cache it -->
  3. {% endcache %}

Setting a specific number of seconds:

  1. {# cache the sidebar by 1 hour #}
  2. {% cache 'sidebar' 3600 %}
  3. <!-- generate this content is slow so we are going to cache it -->
  4. {% endcache %}

Any valid expression can be used as cache key:

  1. {% cache ('article-' ~ post.id) 3600 %}
  2. <h1>{{ post.title }}</h1>
  3. <p>{{ post.content }}</p>
  4. {% endcache %}

The caching is done by the Phalcon\Cache component via the view component. Learn more about how this integration works in the section Caching View Fragments.

Inject Services into a Template

If a service container (DI) is available for Volt, you can use the services by only accessing the name of the service in the template:

  1. {# Inject the 'flash' service #}
  2. <div id='messages'>{{ flash.output() }}</div>
  3. {# Inject the 'security' service #}
  4. <input type='hidden' name='token' value='{{ security.getToken() }}'>

Stand-alone component

Using Volt in a stand-alone mode can be demonstrated below:

  1. <?php
  2. use Phalcon\Mvc\View\Engine\Volt\Compiler as VoltCompiler;
  3. // Create a compiler
  4. $compiler = new VoltCompiler();
  5. // Optionally add some options
  6. $compiler->setOptions(
  7. [
  8. // ...
  9. ]
  10. );
  11. // Compile a template string returning PHP code
  12. echo $compiler->compileString(
  13. "hello"
  14. );
  15. // Compile a template in a file specifying the destination file
  16. $compiler->compileFile(
  17. 'layouts/main.volt',
  18. 'cache/layouts/main.volt.php'
  19. );
  20. // Compile a template in a file based on the options passed to the compiler
  21. $compiler->compile(
  22. 'layouts/main.volt'
  23. );
  24. // Require the compiled templated (optional)
  25. require $compiler->getCompiledTemplatePath();

External Resources