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. 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 2.x features.

How to use Twig

Environment variables

The following environment variables are available:

cID
cType
cVersion
equivId
isDraft
alias
langId
adminId
userId
vars

So to make them appear in the output, you could do this:

<pre>cID={{cID|escape}}
cType={{cType|escape}}
cVersion={{cVersion|escape}}
equivId={{equivId|escape}}
isDraft={{isDraft|escape}}
alias={{alias|escape}}
langId={{langId|escape}}
adminId={{adminId|escape}}
userId={{userId|escape}}
vars={{var_dump(vars)|escape}}</pre>

Note that each is escaped for good measure.

 

Variables

Variables can be set using the {% set %} tag.

Twig snippet variable

These variables may later be used in conditional statements.

Loops

Twig supports looping over items in a sequence.

The following code will display all numbers 0-10 in one row:

Twig snippet numbers 0 to 10

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.

Twig snippet comment

Example

The following code will display the server time and timezone.

Twig snippet server time and timezone

Output:

Twig snippet server time and timezone result