Leanplum Templating Language

Leanplum’s templating language is based on Jinja, a popular templating system that is both simple and powerful. Templates give you the highest degree of control to customize and personalize the content you send to your users.

To use templates, simply mark up any variable or message field with special syntax. Insert variables by surrounding them with {{ }}. For example,

{{ userAttribute.firstName }}

inserts the user attribute labeled “firstName”.

Tags are marked with {% %}. They control the logic of the template, and can perform conditional statements, loops, macros, and more.

Here is an example of a loop:

{% for item in linkedData.menu %}
   <li><a href="{{ item.href }}">{{ item.name }}</a></li>
{% endfor %}

Variables

Template variables, not to be confused with Leanplum’s content variables, contain the data used to render the template. You can define your own variables as well as use built-in variables. Variables can also be expressions, which evaluates to a new variable. Anything in a {{ }} gets evaluated and inserted into the final content.

Some variables are actually a collection of attributes, which can be accessed using a dot (.), or with subscript notation ([]). For example, userAttributes is a collection of all of the user attributes for the current user. If you want to insert the value of an attribute named firstName, either of these will work:

Welcome, {{ userAttribute.firstName }}
Welcome, {{ userAttribute['firstName'] }}

 If the attribute has a space in the name, you must use the subscript notation:

Welcome, {{ userAttribute['First name'] }}

Default Values

When a variable refers to something that’s missing, its value will be null. Null values are treated specially. If you try to render a null value within a message, the message will not be sent for that user.

In this example, if we don’t have the user’s first name, this message would not be sent:

Welcome, {{ userAttribute['First name'] }}

If you want your message to be sent to all of your users, then you need to provide a default value when you are missing information:

Welcome, {{ userAttribute['First name']|default('user') }}

Alternatively, you can also use if statements to provide two different messages:

{% set firstName = userAttribute['First name'] %}
  {% if firstName %}
    Welcome, {{ firstName }}
  {% else %}
    Welcome!
{% endif %} 

Built-in Variables

Leanplum includes many predefined variables to access user profile data. New variables may be added over time. To preserve compatibility, any custom variables you declare has precedence over the built-in variables.

Behavioral Data

Behavioral data include information about a user’s activity, such as what events and states they have triggered. 

Variable Name Data Type Description
appVersion String Which version of your app the user is using.
firstOccurrenceOf['event or state name'] Date The time that the event or state first occurred. Dates can be formatted using the date filter.
lastOccurrenceOf['event or state name'] Date The time that the event or state last occurred.
occurrencesOf['event or state name'] Integer The number of times the user has tracked the event or state.
valueOf['event name'] Number The lifetime value of a particular event
lifetimeValue Number The user’s lifetime value designated by the purchase event.

Lifecycle Data

Lifecycle data include information about when and how often a user is engaging with your app.

Variable Name Data Type Description
numPriorSessions Integer The number of sessions recorded in the user’s lifetime.
firstRun Date The time that the user was first seen.
lastActive Date The time that the user was last active.
minutesSpentInApp Number The number of lifetime minutes spent in the app.

Localization Data

Localization data include the user’s location and localization preferences.

Variable Name Data Type Description
country String The user’s country code.
region String The user’s region (state, province, etc.)
city String The user’s city.
locale String The user’s locale code.
language String The user’s language code.
timezone String The user’s timezone code.

Technology Data

Technology data contain information about the user’s current device.

Variable Name Data Type Description
deviceId String The user’s current device ID.
deviceModel String The user’s current device model.
osName String The user’s current OS name (e.g. iOS, Android)
osVersion String The user’s current OS version.
browserNam String The user’s current browser name.
browserVersion String The user’s current browser version.
pushEnabled Boolean Whether the user can receive push notifications, including data-only notifications.
textPushEnabled Boolean Whether the user can receive push notifications that can display text.

Traffic Source Data

Traffic source data tell you where your users came from before installing your app. To use these, you need to set up an integration with one of our attribution partners. See partners.

Variable Name Data Type Description
sourcePublisherId String The publisher ID of the referrer.
sourcePublisher String The publisher name of the referrer.
sourceSubPublisher String The sub publisher name of the referrer.
sourceSite String The site name of the referrer.
sourceCampaign String The campaign name of the referrer.
sourceAdGroup String The ad group name of the referrer.
sourceAd String The ad name of the referrer.

User Data

User data contain the user’s ID and custom attributes.

Variable Name Data Type Description
developerMode Boolean Whether the user is a developer.
userBucket Integer The user’s randomized bucket from 0-999, used for randomizing content to different groups of users.
userId String The user’s ID, which may be the device ID if no user ID was provided.
userAttribute['attribute name'] String A custom user attribute value within the user’s profile.

Contextual Data

For triggered messages, contextual variables are used to access information about the trigger that activated the message. For example, a shopping cart abandonment message could be triggered by an “Add to Cart” event. This event may contain parameters including the item, quantity, and price of the item that was added to the cart.

Variable Name Data Type Description
value Any A custom value that may be provided when calling the sendMessage API programmatically.
parameter['parameter name'] String The value of a parameter of the event or state that triggered the message.
previousValue String The previous value of the user attribute change that triggered the message.
currentValue String The current value of the user attribute change that triggered the message.
triggerTime Date The time that the initial trigger occurred.

For the above example, assuming 1) you have set the "item" parameter on the "Add to Cart" Event and 2) you are trigger a message based on that same Event, you could add the item name into your message with:

{{parameter['item']}}

Linked Data

Linked data allows you to connect your user profile data with data stored in other sources, like in your own data warehouse or within another service provider. Some examples of linked data include real-time information such as whether an item is in stock, whether a flight is on time or delayed, weather forecasts, or inferred demographic data based on the current user’s attributes.

You can set up linked data sources in your app settings on the Leanplum dashboard. Linked data sources have a name and a URL of the source. The URL itself can be a Leanplum template, which can in turn include other information from a user’s profile. The URL may also include empty placeholders ({}) which must be filled in when accessing the data source.

**Needs to be whitelisted - Contact your CSM or support@leanplum.com for more information

All linked data sources are accessed from the linkedData variable:

Variable Name Data Type Description
linkedData['data source'] String, Array, or Dictionary Data available from a particular named data source defined in your app settings. If possible, the data may be cached for several minutes to reduce repeated requests to the particular source. If the data source outputs JSON data, the data is parsed as a dictionary or array, which can be accessed further using loops or dot notation.
linkedData['data source'][arg1][arg2][...] String, Array, or Dictionary For parameterized data sources, specify the appropriate number of arguments using dot or subscript notation to fill in all of the missing placeholders.

Example: You may have a “menu” data source which emits the following JSON:

{
  "date": "March 10, 2016",
  "items": [
    {
      "name": "Lasagna",
      "image": "http://mydomain.com/images/1001.jpg",
      "price": 11
    }, {
      "name": "Ravioli",
      "image": "http://mydomain.com/images/1002.jpg",
      "price": 12
    }, {
      "name": "Pizza",
      "image": "http://mydomain.com/images/1003.jpg",
      "price": 10
    }
  ]
}

To render the menu in a template, you may use the following markup:

{% for item in linkedData.menu.items %}
  <div>
    <h2>{{ item.name }}: ${{ item.price|round(2) }}</h2>
    <img src="{{ item.image }}" />
  </div>
{% endfor %}

Example: You may have an “item” data source with a parameter for the item SKU, which looks up information about a particular product.

{
  "inStock": true,
  "price": 39.99
}

You can display the price of an item with this template:

The price of the item is 
{{ linkedData.item[parameter.itemSku].price|numberformat('$#,###.00') }}.

Missing Data

In the above example, if there was a problem retrieving the data, the price would be null. Leanplum will automatically skip sending the message if a null value is rendered within a message.

In the next example, we display if the item is in stock. Here, we are not rendering a null value, so we need to explicitly skip the message using skipmessage().

{% set item = linkedData.item[parameter.itemSku] %}
{% if item == null %}
 {{ skipmessage() }}
{% elif item.inStock %}
 Your item is in stock at {{ userAttribute.preferredStore }}!
{% else %}
  Your item is not in stock at this time. 
We’ll notify you when it becomes available. {% endif %}

Filters

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses.  You can either settle the variable beforehand, or reference it directly.

For example, {{ variable|capitalize }} will capitalize outputted text.

{% set city = userAttributes['favoriteCity'] %}
{{ city|capitalize }}

OR

{{ userAttributes['favoriteCity']|capitalize }}

Chaining

Multiple filters can be chained. The output of one filter is applied to the next.

For example, {{ name|striptags|title }} will remove all HTML Tags from variable name and title-case the output (title(striptags(name))).

Arguments

Filters that accept arguments have parentheses around the arguments, just like a function call. For example: {{ listx|join(', ') }} will join a list with commas (str.join(', ', listx)).

See List of Built-in Filters.

Expression Tests

Beside filters, there are also so-called “tests” available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out if a variable is defined, you can do name is defined, which will then return true or false depending on whethername is defined in the current template context.

Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:

{% if loop.index is divisibleby 3 %}
{% if loop.index is divisibleby(3) %}

The List of Built-in Expression Tests describes all the builtin expression tests.

Comments

To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #}. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:

{# note: commented-out template because we no longer use this
    {% for user in users %}
        ...
    {% endfor %}
#}

Escaping

It is sometimes desirable – even necessary – to have Leanplum ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you have to use a trick.

The easiest way to output a literal variable delimiter ({{) is by using a variable expression:

{{ '{{' }}

For bigger sections, it makes sense to mark a block raw. For example, to include example Leanplum template syntax in a template, you can use this snippet:

{% raw %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endraw %}

HTML Escaping

When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML.

It’s your responsibility to escape variables if needed. What to escape? If you have a variable that may include any of the following chars (>, <, &, or ") you SHOULD escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter:

{{ user.username|e }}

List of Control Structures

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %} blocks.

For

Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

<h1>Members</h1>
<ul>
{% for user in users %}
  <li>{{ user.username|e }}</li>
{% endfor %}
</ul>

Inside of a for-loop block, you can access some special variables:

Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
loop.depth Indicates how deep in deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in deep in a recursive loop the rendering currently is. Starts at level 0

Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special cycle helper:

{% for row in rows %}
    <li class="{% cycle('odd', 'even') %}">{{ row }}</li>
{% endfor %}

You can call variables that are defined outside of a loop, from within a loop, but not the other way around.

If

In the simplest form, you can use it to test if a variable is defined, not empty or not false:

{% if userAttribute.interests %}
Your interests:
<ul>
{% for interest in userAttribute.interests %}
    <li>{{ interest|e }}</li>
{% endfor %}
</ul>
{% endif %}

For multiple branches, elif and else can be used too:

{% if userAttribute.membership == 'Gold' %}
You are a Gold member!
{% elif userAttribute.membership == 'Silver' %}
You are a Silver member!
{% else %}
Please become a member today!
{% endif %}

Macros

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).

Here’s a small example of a macro that renders a form element:

{% macro input(name, value='', type='text', size=20) -%}
    <input type="{{ type }}" name="{{ name }}" value="{{
        value|e }}" size="{{ size }}">
{%- endmacro %}

The macro can then be called like a function in the namespace:

<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>

If the macro was defined in a different template, you have to import it first.

Inside macros, you have access to three special variables:

varargs If more positional arguments are passed to the macro than accepted by the macro, they end up in the special varargs variable as a list of values.
kwargs Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special variable.
caller() The contents of the call block that called this macro.

In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special call block. The following example shows a macro that takes advantage of the call functionality and how it can be used:

{% macro render_dialog(title, class='dialog') -%}
    <div class="{{ class }}">
        <h2>{{ title }}</h2>
        <div class="contents">
            {{ caller() }}
        </div>
    </div>
{%- endmacro %}

{% call render_dialog('Hello World') %}
    This is a simple dialog rendered by using a macro and
    a call block.
{% endcall %}

Assignments

Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or loops) are exported from the template like top level macros and can be imported by other templates.

Assignments use the set tag and can have multiple targets:

{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
{% set key, value = call_something() %}

Other Tags

See the List of Built-in Tags.

Expressions

Leanplum allows basic expressions everywhere. Expressions can be used to create variables from other variables or expressions, such as by performing mathematical, logical, or other operations.

Literals

The simplest form of expressions are literals. Literals represent variables like strings and numbers. The following literals exist:

“Hello World” Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template).
42 / 42.23 Integers and floating point numbers are created by just writing the number down. If a dot is present, the number is a float, otherwise an integer. Keep in mind that 42 and 42.0 are different (int and float, respectively).
['list', 'of', 'objects'] Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop:
<ul>
{% for href, caption in [
('index.html', 'Index'),
('about.html', 'About'), ('downloads.html', 'Downloads')
] %} <li><a href="{{ href }}">
{{ caption }}
</a></li> {% endfor %} </ul>
{'dictionary': 'of',
'key': ‘and',
'value': 'pairs'}
A dictionary combines keys and values. Keys must be unique and always have exactly one value. Dictionaries are rarely created, but they’re used when reading data from other sources.
true / false true is always true and false is always false.

Math

Leanplum allows you to calculate with values. The following operators are supported:

+ Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the ~ operator.{{ 1 + 1 }} is 2.
- Subtract the second number from the first one. {{ 3 - 2 }} is 1.
/ Divide two numbers. The return value will be a floating point number. {{ 1 / 2 }}is {{ 0.5 }}.
% Calculate the remainder of an integer division. {{ 11 % 7 }} is 4.
* Multiply the left operand with the right one. {{ 2 * 2 }} would return 4.

Comparisons

== Compares two objects for equality.
!= Compares two objects for inequality.
> true if the left hand side is greater than the right hand side.
>= true if the left hand side is greater or equal to the right hand side.
< true if the left hand side is lower than the right hand side.
<= true if the left hand side is lower or equal to the right hand side.

Logic

For if statements, for filtering, and if expressions, it can be useful to combine multiple expressions:

and Return true if the left and the right operand are true.
or Return true if the left or the right operand are true. Or can also be used to deal with default values. For example, the following will return the user’s name if it exists; otherwise, it will return the user’s email:
{{ userAttribute.name or userAttribute.email }}
not negate a statement (see below).
(expr) group an expression.

Other Operators

The following operators are very useful but don’t fit into any of the other two categories:

in Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. {{ 1 in [1, 2, 3] }} would, for example, return true.
is Performs an expression test.
| Applies a filter.
~ Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John') HelloJohn!.
() Call a callable: {{ post.render() }}. Inside of the parentheses you can use positional arguments and keyword arguments:
{{ post.render(user, full=true) }}.
. / [] Get an attribute of an object. (See Variables).

List of Built-in Filters

abs

Return the absolute value of the argument.

Parameters

number number   The number that you want to get the absolute value of

add

adds a number to the existing value

Parameters

number number   Number or numeric variable to add to
addend number   The number added to the base number

attr

Renders the attribute of a dictionary

Parameters

obj String Default value: '' The dictionary containing the attribute
name String Default value: '' The dictionary attribute name to access

batch

A filter that groups up items within a sequence

Parameters

value String Default value: '' The sequence or dict that the filter is applied to
linecount number Default value: 0 Number of items to include in the batch
fill_with String Default value: '' Value used to fill up missing items

capitalize

Capitalize a value. The first character will be uppercase, all others lowercase.

Parameters

string String Default value: '' String to capitalize the first letter of

center

Uses whitespace to center the value in a field of a given width.

Parameters

value String Default value: '' Value to center
width number Default value: 80 Width of field to center value in

count

Alias of length

cut

Removes a string from the value from another string

Parameters

value String Default value: '' The original string
to_remove String Default value: '' String to remove from the original string

d

Alias of default

date

Alias of datetimeformat

datetimeformat

Formats a date object

Parameters

value String Default value: 'current time' The date variable or UNIX timestamp to format
format String Default value: '%H:%M / %d-%m-%Y' The format of the date determined by the directives added to this parameter

default

If the value is undefined it will return the passed default value, otherwise the value of the variable

Parameters

value String Default value: '' The variable or value to test
default_value String Default value: '' Value to print when variable is not defined
boolean boolean   Set to True to use with variables which evaluate to false

dictsort

Sort a dict and yield (key, value) pairs.

Parameters

value String Default value: '' Dict to sort
case_sensitive boolean   Determines whether or not the sorting is case sensitive
by enum key|value Default value: key Sort by dict key or value

divide

Divides the current value by a divisor

Parameters

value number   The numerator to be divided
divisor number   The divisor to divide the value

divisible

Evaluates to true if the value is divisible by the given number

Parameters

value number   The value to be divided
divisor number   The divisor to check if the value is divisible by

e

Alias of escape

escape

Converts the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this filter if you need to display text that might contain such characters in HTML. Marks return value as markup string.

Parameters

s String Default value: '' String to escape

filesizeformat

Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc).

Parameters

value String Default value: '' The value to convert to filesize format
binary boolean   Use binary prefixes (Mebi, Gibi)

first

Return the first item of a sequence.

Parameters

seq sequence   Sequence to return first item from

float

Convert the value into a floating point number.

Parameters

value String Default value: '' Value to convert to a float
default float Default value: 0.0 Value to return if conversion fails

forceescape

Enforce HTML escaping. This will probably double escape variables.

Parameters

value String Default value: '' Value to escape

groupby

Group a sequence of objects by a common attribute.

Parameters

value String Default value: '' The dict to iterate through and group by a common attribute
attribute String Default value: '' The common attribute to group by

indent

Uses whitespace to indent a string.

Parameters

s String Default value: '' The string to indent
width number Default value: 4 Amount of whitespace to indent
indentfirst boolean   If True, first line will be indented

int

Convert the value into an integer.

Parameters

value String Default value: '' The value to convert to an integer
default number Default value: 0 Value to return if the conversion fails

join

Return a string which is the concatenation of the strings in the sequence.

Parameters

value String Default value: '' The values to join
d String Default value: '' The separator string used to join the items
attr String Default value: '' Optional dict object attribute to use in joining

last

Return the last item of a sequence

Parameters

seq sequence   Sequence to return last item from

length

Return the number of items of a sequence or mapping

Parameters

object String Default value: '' The sequence to count

list

Convert the value into a list. If it was a string the returned list will be a list of characters.

Parameters

value String Default value: '' Value to add to a sequence

lower

Convert a value to lowercase

Parameters

s String Default value: '' String to make lowercase

map

Applies a filter on a sequence of objects or looks up an attribute.

Parameters

value object   Sequence to apply filter or dict to lookup attribute
attribute String Default value: '' Filter to apply to an object or dict attribute to lookup

md5

Calculates the md5 hash of the given object

Parameters

value String Default value: '' Value to get MD5 hash of

multiply

Multiplies the current object with the given multiplier

Parameters

value number   Base number to be multiplied
multiplier number   The multiplier

numberformat

Formats a number.

Parameters

value number   Number to be formatted
formatSpec String Default value: '' Format spec. Use 0 to represent a required digit, # an optional digit, dot (.) to represent a decimal separator, and (,) to represent a grouping separator. For more information, see https://docs.oracle.com/javase/tutorial/ i18n/format/decimalFormat.html.

pprint

Pretty print a variable. Useful for debugging.

Parameters

value object   Object to Pretty Print

random

Return a random item from the sequence.

Parameters

seq sequence   Sequence to return a random item from

reject

Filters a sequence of objects by applying a test to the object and rejecting the ones with the test succeeding.

Parameters

seq Sequence to test    
exp_test name of expression test Default value: truthy Specify which expression test to run for making the selection

rejectattr

Filters a sequence of objects by applying a test to an attribute of an object or the attribute and rejecting the ones with the test succeeding.

Parameters

seq sequence   Sequence to test
attribute String Default value: '' Attribute to test for and reject items that contain it
exp_test name of expression test Default value: truthy Specify which expression test to run for making the rejection

replace

Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument count is given, only the first count occurrences are replaced

Parameters

s String Default value: '' Base string to find and replace within
old String Default value: '' The old substring that you want to match and replace
new String Default value: '' The new string that you replace the matched substring
count number   Replace only the first N occurrences

reverse

Reverse the object or return an iterator the iterates over it the other way round.

Parameters

value object   The sequence or dict to reverse the iteration order

round

Round the number to a given precision.

Parameters

value number   The number to round
precision number Default value: 0 Specifies the precision of rounding
method enum common|ceil|floor Default value: common Method of rounding: 'common' rounds either up or down, 'ceil' always rounds up, and 'floor' always rounds down.

Examples

Note that even if rounded to 0 precision, a float is returned.

{{ 42.55|round }}

Output: 43.0

If you need a real integer, pipe it through int

{{ 42.55|round|int }}

Output: 43

safe

Mark the value as safe, which means that in an environment with automatic escaping enabled this variable will not be escaped.

select

Filters a sequence of objects by applying a test to the object and only selecting the ones with the test succeeding.

Parameters

value sequence    
exp_test name of expression test Default value: truthy Specify which expression test to run for making the selection

selectattr

Filters a sequence of objects by applying a test to an attribute of an object and only selecting the ones with the test succeeding.

Parameters

sequence sequence   Sequence to test
attr String Default value: '' Attribute to test for and select items that contain it
exp_test name of expression test Default value: truthy Specify which expression test to run for making the selection

shuffle

Randomly shuffle a given list, returning a new list with all of the items of the original list in a random order

slice

Slice an iterator and return a list of lists containing those items.

Parameters

value sequence   The sequence or dict that the filter is applied to
slices number   Specifies how many items will be sliced
fill_with String Default value: '' Used to fill missing values on the last iteration

sort

Sort an iterable.

Parameters

value iterable   The sequence or dict to sort through iteration
reverse boolean   Boolean to reverse the sort order
case_sensitive boolean   Determines whether or not the sorting is case sensitive
attribute String Default value: '' Specifies an attribute to sort by

split

Splits the input string into a list on the given separator

Parameters

s String Default value: '' The string to split
separator String Default value: ' ' Specifies the separator to split the variable by
limit number Default value: 0 Limits resulting list by putting remainder of string into last list item

string

Returns string value of object

striptags

Strip SGML/XML tags and replace adjacent whitespace by one space.

sum

Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.

Parameters

value iterable   Selects the sequence or dict to sum values from
attribute String Default value: '' Specify an optional attribute of dict to sum
start number Default value: 0 Sets a value to return, if there is nothing in the variable to sum

title

Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.

trim

Strip leading and trailing whitespace.

truncate

Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter.

Parameters

s String Default value: '' The string to truncate
length number Default value: 255 Specifies the length at which to truncate the text (includes HTML characters)
killwords boolean   If true, the string will cut text at length
end String Default value: '...' The characters that will be added to indicate where the text was truncated

truncatehtml

Truncates a given string, respecting html markup (i.e. will properly close all nested tags)

Parameters

html String Default value: '' HTML to truncate
length number Default value: 255 Length at which to truncate text (HTML characters not included)
end String Default value: '...' The characters that will be added to indicate where the text was truncated
breakword boolean   If set to true, text will be truncated in the middle of words

unique

Extract a unique set from a sequence of objects

Parameters

sequence sequence   Sequence to filter
attr Optional attribute on object to use as unique identifier    

Examples

Filter duplicated strings from a sequence of strings

{{ ['foo', 'bar', 'foo', 'other']|unique|join(', ') }}

Output: foo, bar, other

upper

Convert a value to uppercase

urlencode

Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.

urlize

Converts URLs in plain text into clickable links.

Parameters

value String Default value: '' string URL to convert to an anchor
trim_url_limit number   Sets a character limit
nofollow boolean   Adds nofollow to generated link tag
target String Default value: '' Adds target attr to generated link tag

wordcount

Counts the words in the given string

wordwrap

Return a copy of the string passed to the filter wrapped after 79 characters.

Parameters

s String Default value: '' String to wrap after a certain number of chracters
width number Default value: 79 Sets the width of spaces at which to wrap the text
break_long_words boolean Default value: True If true, long words will be broken when wrapped

xmlattr

Create an HTML/XML attribute string based on the items in a dict.

Parameters

d dict   Dict to filter
autospace boolean Default value: True Automatically prepend a space in front of the item

List of Built-in Expression Tests

defined

Return true if the variable is defined

divisibleby

Check if a variable is divisible by a number

Parameters

num number   The number to check whether a number is divisble by

equalto

Check if an object has the same value as another object

Parameters

other object   Another object to check equality against

even

Return true if the value is even

iterable

Return true if the object is iterable (sequence, dict, etc)

lower

Return true if the given string is all lowercased

mapping

Return true if the given object is a dict

newerthan

Return true if version A is newer than version B.

none

Return true if the given object is null / none

number

Return true if the object is a number

odd

Return true if the object is an odd number

olderthan

Return true if version A is older than version B.

sameas

Return true if variable is pointing at same object as other variable

Parameters

other object   A second object to check the variables value against

sequence

Return true if the variable is a sequence. Sequences are variables that are iterable.

string

Return true if object is a string

truthy

Return true if object is 'truthy'

undefined

Return true if object is undefined

upper

Return true if string is all uppercased

List of Built-in Tags

block

(Coming soon) Blocks are regions in a template which can be overridden by child templates

Parameters

block_name String Default value: '' A unique name for the block that should be used in both the parent and child template

call

In some cases it can be useful to pass a macro to another macro. For this purpose you can use the special call block.

cycle

The cycle tag can be used within a for loop to cycle through a series of string values and print them with each iteration

Parameters

string_to_print String Default value: '' A comma separated list of strings to print with each interation. The list will repeat if there are more iterations than string parameter values.

extends

(Coming soon) Template inheritance allows you to to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

Parameters

template_nmae String Default value: '' Name of parent template

for

Outputs the inner content for each item in the given iterable

Parameters

items_to_iterate String Default value: '' Specifies the name of a single item in the sequence or dict.

from

(Coming soon) Alternative to the import tag that lets you import and use specific macros from one template to another

Parameters

template_nmae String Default value: '' Template to to import from
macro_name String Default value: '' Name of macro or comma separated macros to import (import macro_name)

if

Outputs inner content if expression evaluates to true, otherwise evaluates any elif blocks, finally outputting content of any else block present

import

(Coming soon) Allows you to access and use macros from a different template

Parameters

template_nmae String Default value: '' Template to to import
import_name String Default value: '' Give a name to the imported template to access macros from

include

includes multiple templates in one template

Parameters

template_nmae String Default value: '' Design Manager template_nmae to the file that you would like to include

macro

Macros allow you to print multiple statements with a dynamic value or values

Parameters

macro_name String Default value: '' The name given to a macro
argument_names String Default value: '' Named arguments that are dynamically, when the macro is run

print

Echos the result of the expression

Parameters

expr expression   Expression to print

raw

Process all inner content as plain text

set

Assigns the value or result of a statement to a variable

Parameters

var variable identifier   The name of the variable
expr expression   The value stored in the variable (string, number, boolean, or sequence

unless

Unless is a conditional just like 'if' but works on the inverse logic.

Parameters

expr expression   Condition to evaluate

List of Built-in Functions

datetimeformat

formats a date to a string

Parameters

var date Default value: current time  
format String Default value: '%H:%M / %d-%m-%Y'  

range

Returns a list of values within a given range.

Parameters

start integer Default value: 0 Starting value of the range
start integer   Ending value of the range
start integer Default value: 1 Amount to increment

skipmessage

Skips sending the current message for the current user.

super

Only usable within blocks, will render the contents of the parent block by calling super.

truncate

truncates a given string to a specified length

Parameters

s String Default value: ''  
length number Default value: 255  
end String Default value: '...'  

Was this article helpful?
Have more questions? Submit a request