Basic Syntax of Jinja

Even though it isn't a programming language, Jinja also has a specific set of words that you need to use in order to write a 'code' in it. Together, they are called the syntax and are governed by a set of simple rules that allow you to tell the computer what you need to achieve in a language comprehensible to it.

You will be mostly writing your Jinja templates directly in the Bloomreach Engagement. However, in general, you can write Jinja templates into a simple text file. You do not need to worry about the file's extension, Jinja does not require a specific file extension and it can generate any text-based format, such as Html, XML, CSV, or LaTeX.

Delimiters

Because Jinja codes are usually inserted into other types of code, such as Html in emails, the difference between the Jinja code and the other parts need to be clearly distinguished. In Jinja, you will use delimiters to signify that this particular part of code is relevant for the parser.

The following table describes the delimiters that you need to use.

Delimiter:It is used for:
{{..}}
For instance {{ customer['first_name'] }} .
Prints the content in between the curly brackets to the template output.
{%..%}
For instance {% set x = 42 %} .
Statements of the Jinja language that do not have an output.
{#..#}
For instance {# We appreciate ducks #}.
Comments to make your Jinja code more comprehensible for other people.

Variables

Another basic feature of Jinja is variables. Sometimes, you need the computer to remember some values while rendering your template. In order to do so, you can create a variable, that will store the value for you. A variable always has a name, by which it can be referred to during the rendering, and it also has a type. However, you do not need to worry about types, for now. Jinja automatically sets them up for you when you initialize a variable.

📘

Variable names

Make sure that you give your variables relevant names. It will make your code more readable and it will also help you eliminate errors. For instance, you can call a variable storing a number x, or a variable storing some customer's name, customerName.

Using your variables

Before you can use your variable, it first needs to be initialized. You can do this by using the set command. However, you always need to initialize your variables with value. For instance, {% set favouriteAnimal = "duck" %} will create a variable called favouriteAnimal and save the word "duck" in it. Then you will be able to use the variable throughout your code by simply typing the variables name.

{% set favouriteAnimal = "duck" %} 
{{ favouriteAnimal }}
Output: duck

When defining a variable, it is possible to use if else and elif statements.

Example with if/else when setting a variable:

{% set first_name = customer.first_name | title if customer.first_name else "Sir/Madam" %}

Example without using if/else when setting variable:

{% set first_name =  "Sir/Madam" %}

{% if customer.first_name %}
    {% set first_name =  customer.first_name | title %}
{% endif %}

{{ first_name }}

📘

Initialising your variable

Make sure you always initialize your variables before using them, otherwise, the parser will not be able to understand what you are referring to by the variable name.

Properties of variables

Sometimes, you might be interested in the properties of some value of your variables. For instance, you would like to know, how many letters does the name of your customer contain. In general, the properties of your customers can be accessed in two ways. First, they can be accessed by using the box brackets.
variable['property'], which returns the property specified in the string between the box brackets from the specified variable, this is the preferred way. You can also access the properties using the dot notation variable.property.

🚧

Box brackets are the preferred option

To avoid unnecessary bugs, you should stick to the box bracket notation variable['property']. Although generally, the two should be equivalent, there are some known cases where using the variable.property causes critical issues. This is because built-in methods of the Python type have precedence.
For a technical explanation of the differences check out this official Jinja reference

Basic variable data types

Data typeWhat does it representExample values
NoneRepresents no or lack of value.none, None
IntegerWhole numbers.42, 12, 3134.
FloatReal numbers (with decimal separator).12.34, 423.52341, 3.1415, 15.0.
StringAny string of characters."dog", "DuCk", "Bloomreach Engagement is cool", "8#jdas#12jndas";

📘

When it comes to data types, Boolean (true/True, false/False) is a subset of Integer.

📘

String notation

When setting out strings, you have to tell the renderer that it is a value of type string, not statements of Jinja. You do this by enclosing the string in either single quotations 'Example' or double quotations "Example".

None value in Jinja

When the none value is returned for example from an aggregate, the Jinja renderer processes it as the string value “None”. This means that if you’re using a campaign to set attribute based on aggregate and the aggregate doesn’t return any value (= returns None), that attribute will have string value “None”.

Other supported data types in Jinja

List
Mutable array, defined with square brackets ( [ ] )
Can contain any data types
E.g. [1, 'string', [ [ ], [ ] ], { 1: 'a' }, none ]
Find more about Lists

Tuple
Like list, but immutable, cannot be changed once defined.
Defined with parenthesis ( ( ) )
Can contain any type
E.g. (1, 'string', [ [ ], [ ] ], { 1: 'a' }, none )
Find more about Tuples

Dictionary
Object containing "key: value" pairs.
Defined with curly brackets ( { } )
Keys can be Strings, Numbers (Integers or Floats), or None.
Value can be any data type.
Find more about Dictionaries

Expressions

Jinja also supports basic expressions. They are built upon the python expressions but should feel easy to use even if you have never had any experience with python. You can see the reference in the Jinja Template Designer Documentation. However, expressions will be covered here too.

Math expressions in Jinja

The most basic expressions in Jinja are the math expressions. You often need to perform math operations on your data and Jinja does contain the elementary operations that you might need to perform. The official documentation for math expressions can be found in Template designer documentation - Math.

Math expressions

  • + Addition.
  • - Subtraction.
  • * Multiplication.
  • / Division.
  • // Returns integer result of division rounded down, e.g. 20 // 7 returns 2.
  • % Calculate the remainder of division. For instance, 11 % 7 returns 4.

❗️

The math expression of a power operand ** is not supported, e.g. {{ 2 ** 16 }} would not work.

Comparison expressions in Jinja

Jinja also inherits the comparison operators from python. They are essential when implementing control flow, which will be covered in a later article. The official documentation for comparison expressions can be found in Template designer documentation - Comparisons.

Comparison operators

  • == 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

Logical expressions in Jinja

You can also evaluate boolean expressions in Jinja using logic operators.

Logic operators in Jinja

  • and Boolean and
  • or Boolean or
  • not Boolean negation

Other expressions in Jinja

Jinja also supports operators which do not fit in any of the previous categories. They are so-called other operators.

Other operators

in
In is used for testing whether a value is contained in a sequence or mapping.
It evaluates to True if the left-hand side is contained in the right-hand side.
It admits Lists, Tuples, Strings and Dictionaries as arguments. However, dictionaries are tested for keys, not for values.
Example: {{ 1 in [1, 2, 3] }} or {​{ 'a' in {'a': 13} }} both of these evaluate to and return True.

is
Is is used for applying tests. Using the is operator performs a test specified by the right-hand side on a variable on the left-hand side. Tests will be covered in a later section.
Example: {{ 'hello' is defined }} returns true.

~
The ~ (read as "tilde") operator is used to join operands as strings. It converts neighboring operands into strings and concatenates them.
Example: {{ 8/2 ~ 'ever' }} prints '4ever'

📘

For more information, go to the Jinja documentation.


What´s next?