How to create a Twig snippet plugin for server-side code

What is Twig and why use it?

Twig is a template engine for PHP. It supports a subset of the server-side PHP language and runs it in a Zenario-controlled environment.

If your site needs to access environment variables about the site, the page in view, the user, date/time information, or other data that you prefer not to get from JavaScript (browser-executable code), it's helpful to use Twig, as it executes on the server before being sent to the browser. 

Twig snippet plugin

Using the Twig snippet module, a Twig snippet plugin can be placed in a slot on a web page.

For security reasons, Twig code cannot be typed in directly, and the Twig snippet must be placed in a file on the server in the zenario_custom/twig directory. Then in the Twig snippet (set up via Zenario in the browser), the administrator can select the appropriate snippet.

When the page loads, after server-side processing, it will display a block of HTML or Javascript.

Security and available functions

For security reasons PHP code will not be executed directly.

See Zenario's Twig functions for a list of functions that Zenario supports.

For basic Twig syntax, and for more guidance, see the Twig documentation.

Zenario supports a subset of the Twig 3 features (Twig 2 up to Zenario 9.7).

How to use Twig

Variables

Variables can be declared using the {% set %} tag, e.g.:

{% set name = 'Joe' %}

These variables may later be used in conditional statements.

Loops

Twig supports looping over items in a sequence.

For example, the following code will display all numbers 0-10 in one row:

{% for number in 0..10 %}
{{number|escape}}
{% endfor %}

Comments

Comments only appear in the source code and are never displayed to users. Use them to explain how code works to other admins.

To use a comment, put the {# ... #} tags around the text, e.g.:

{# This is an example of a comment. #}

Accessing Zenario's environment variables

When writing a Twig snippet, the CMS will pre-declare a few variables for you.

The following environment variables related to the current content item will be available:

The following environment variables related to the current user will be available:

And finally, the following variables related to the current plugin will be available:

For example:

<div class="plugin_title" id="{{containerId|escape}}_title">Hello world!</div>

Accessing Zenario's function library

Any Zenario function that has been whitelisted for use in Twig can be called using the ze() function.

You can also use the |trans filter as a shortcut to the phrase() function.

For example, this following code could be used to display a welcome message to the currently logged in user:

{% set firstName = ze('user', 'firstName') %}
{% if firstName %}
  <h1>{{"Welcome"|trans}}, {{firstName|escape}}</h1>
{% endif %}