Twig Reference (Legacy) - xenocrat/chyrp-lite GitHub Wiki
This document provides information on the version of Twig integrated with Chyrp Lite's "Saxaul" and "Kordofan" releases. Please read the Twig Reference for further information on the version of Twig integrated with newer releases of Chyrp Lite.
Twig is Chyrp Lite's template engine, created for Chyrp by Armin Ronacher. The syntax in general is “similar to the Genshi text templates which in turn were inspired by Django which also inspired Jinja (all three of them python template engines) which inspired the Twig runtime environment.”
Files written for the Twig template engine are known as twigs and use a ".twig" file extension.
{% (this is a block) %}
${ (this is an expression) }
$this_is_a_variable
${ this_is_also_a_variable }
${ variable | this_is_a_filter("and", "these are", arguments) }
$variable.these.are.attributes
this == is + an ~ "expression"
{# this is a comment, and is removed when the template is built #}
Here’s a an example of the syntax used by Twig for performing various functions:
<!DOCTYPE HTML>
{# This is a comment #}
<title>{% block title %}Page Title Goes Here{% endblock %}</title>
{% if show_navigation %}
<nav>
<ul>
{% for item in navigation %}
<li><a href="${ item.href | escape }">$item.caption</a></li>
{% endfor %}
</ul>
</nav>
{% endif %}
<article>
{% block body %}
{% for article in articles %}
$article.title
{% else %}
There aren't any articles!
{% endfor %}
{% endblock %}
</article>
To simply output the value of a variable using Twig, prefix it with a $
dollar sign, for example $foo
. Use a .
(period) to access attributes of that variable or call a function of that name, for example $foo.bar
. Be careful when using a variable at the end of a sentence where a period occurs. In that case, you may want to wrap the variable in filtering syntax, “such as in this ${ example }
.”
Variables are passed as a context array upon loading the template file. A list of common context variables can be found in the article Twig Variables.
Blocks define an area of content that can be populated by another twig file. If the content area is not populated by another twig, the block will display its own content instead. Blocks are defined like so:
{% block myblock %}
Here's some default content!
{% endblock %}
To import the contents of a twig file in another, use {% include "path/to/file.twig" %}
. A common use for include
is to import tertiary page elements, for example a sidebar, allowing a theme to be split into multiple files.
The paths used in {% include %}
and {% extends %}
are POSIX paths relative to the directory the Twig lexer was initiated to read from (for blog themes, the path is relative to "themes/yourtheme/").
To make a comment in your template file, simply surround it with {# these #}
curly brackets and hashes, and it will be ignored by the lexer.
Filters are used to manipulate a value and return the result. The most basic form of an expression in Twig is by “piping” the data to a “filter”. When applying a filter to a variable, encapsulate the entire expression in curly brackets prefixed with ${ }
a dollar sign; in this case, there is no need to prefix the variable. For example, ${ post.title | lower | truncate(40) }
would return the title of the post, converted to lowercase, and truncated to 40 characters.
Name | Description |
---|---|
camelize |
Convert string to camelcase. |
capitalize |
Like title , but capitalizes only the first character of the whole string. |
checked |
Same as selected , but outputs checked="checked" . |
contains |
Searches a string and returns true if it contains the supplied substring. |
count |
Count the number of items in an array, or characters in a string. |
date |
Format the timestamp using the PHP date formatting rules. |
default |
If the value is none the first argument is returned. |
escape or e
|
Escape HTML in the string. |
even |
Returns true if the number is even. |
fallback |
If the value is empty or none, return this value. |
filesizeformat |
Takes a number of bytes and displays it as KB/MB/GB. |
first |
First entry of an Array. |
format |
Applies sprintf formatting on the string. |
gravatar |
Retrieve an avatar image for the user, optionally within an <img> tag. |
inspect |
Dumps the variable or value. |
items |
Items of an Array. |
join |
Concatenate the array items and join them with the string provided (or commas by default). |
keys |
Keys of an Array. |
last |
Last entry of an Array. |
length |
Alias for count . |
linebreaks |
Convert linebreaks to <br /> . |
lower |
Convert the string to lowercase. |
lstrip |
Trim leading whitespace. |
moneyformat |
Like numberformat but for money. |
normalize |
Convert all excessive whitespace (including linebreaks) into a single space. |
numberformat |
Apply number formatting on the string. This may or may not use local specific rules. |
odd |
Returns true if the number is odd. |
offset |
Entry at Array[offset]. |
option_selected |
Same as selected , but outputs selected="selected" . |
pluralize |
Return the pluralization of a string, or if a number is passed and it is 1, don’t pluralize. |
replace |
Replaces the occurrence of the first argument with the second argument in the string. If the third argument is true , it will use regular expressions. |
reverse |
Reverse the Array items. |
rstrip |
Trim trailing whitespace. |
sanitize |
Remove special characters from a string. |
sanitize_html |
Disable scripts and obnoxious attributes in HTML strings. |
selected |
If the first argument is the same as the value, output class="selected" , or selected if the second argument is true . |
split |
Split a string into an array at the given breakpoints. |
strftime |
Format the timestamp using standard strftime rules. |
strip |
Trim leading and trailing whitespace. |
strip_tags |
Strip HTML from the string. |
title |
Make the string lowercase, then upper case the first characters of all words. |
translate |
Translate the string using either the “theme” domain or the “admin” domain if in Admin. |
translate_plural |
Translate the (singular) string, or the plural string if the number passed is not 1. |
truncate |
Truncate a string, providing ellipsis, if it is longer than the passed length. Keeps words in tact by default, but with a second boolean parameter will be strict. |
quotes |
Escape quotes (\’, ", etc.) |
upper |
Convert the string to uppercase. |
urlencode |
URL encode the string. If the second parameter is true this function will encode for path sections, otherwise for query strings. |
The following operators can be used in {% blocks %}
and ${ expressions }
:
Operator | Description |
---|---|
== |
Does the left expression equal the right expression? |
!= |
Is the left expression not equal to the right expression? |
+ |
Convert both arguments into a number and add them. |
- |
Convert both arguments into a number and substract them. |
* |
Convert both arguments into a number and multiply them. |
/ |
Convert both arguments into a number and divide them. |
% |
Convert both arguments into a number and calculate the rest of the integer division. |
~ |
Convert both arguments into a string and concatenate them. |
or |
True if the left or the right expression is true. |
and |
True if the left and the right expression is true. |
not |
Negate the expression. |
An if
statement evaluates an expression and if the result is true
the contents of the block is processed up to the mandatory endif
. You can insert an elseif
statement to evaluate further expressions if the first returns false
and an else
statement to handle a terminal false
result. For example:
{% if condition %}
If @condition@ evaluates to @true@, you'll see me!
{% elseif condition2 %}
If @condition1@ is @false@, but @condition2@ is @true@, you'll see me!
{% else %}
If neither are @true@, I'll show up and be all mopey about it.
{% endif %}
For more complex operations, you can wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
A for
loop is used to traverse arrays. {% else %} may be used if the array is empty. The syntax is very simple:
{% for page in pages %}
Page #$page.id
{% else %}
There aren't any pages!
{% endfor %}
When iterating over keys and values of an associative array, use the syntax {% for key, val in arr | items %}
(note the items filter). This is the equivalent of foreach ($arr as $key => $val):
in PHP.
Using loops provides a loop
variable that is available within the scope of the loop. Its attributes are as follows:
Variable | Description |
---|---|
loop.first |
Is this the first item in the loop? |
loop.last |
Is this the last item in the loop? |
loop.index |
Offset of the current loop from the beginning, starting at 1. |
loop.index0 |
Offset of the current loop from the beginning, starting at 0. |
loop.revindex |
Offset of the current loop from the end, ending at 1. |
loop.revindex0 |
Offset of the current iteration from the end, ending at 0. |
loop.parent |
If the loop is nested within another loop, the loop “above” this one. |