Jinja2 syntax
Comments
{# a comment -#}
variables
You have access to the same base-variables that you would in python, but scope is treated very differently.
{% set variable = 3 %} my_variable: {{ variable }} {% set mylist = [ 'a', 'b', ] %} {% do mylist.append( 'c' ) %} {% set mydict = {'a':0} %} {% do mydict.update( {'b':1} ) %}It is very important to note that scope is treated very differently than it is in Python. Normal variable scope is contained within it's if-statement or for-loop. This means if you are trying to modify a variable to create an exit-condition, under normal circumstances it will not work.
This can be worked around by using a list or a dict, and rather than using
set
to set the value, usedo
to update/append a value. Lists/Dicts when used this way have scope within the entire file.
{% set exit_condition = [] %} {% for item in mylist %} {% if not exit_condition %} ... {% endif %} {% do exit_condition.append(1) %} {% endfor %}
loops
filters
Filters are exceptionally useful, they provide a lot of the conveniences you are used to from python. See http://jinja.pocoo.org/docs/dev/templates/#builtin-filters
custom filters
import jinja2 def pad( value, padding ): """ padding ex: '###' """ return str(value).zfill( len(padding) ) env = jinja2.Environment( loader=jinja2.DictLoader({}) ) env.filters['pad'] = pad template = env.from_string( '/some/file/path{{ 1 | pad("###") }}.ma' ) template.render() >>> '/some/file/path001.ma'
join
{% set mylist = ['a','b','c'] %} my_list_items: {{ mylist | join(" ") }} ## 'a b c'replace
{% set mystr = "j jonah jameson" %} my_newstr: {{ mystr | replace( "j" "J ) }} ## 'J Jonah Jameson'
objects/functions
In addition to passing a dictionary of variable-values to jinja, you can pass functions/objects!
from __future__ import unicode_literals import jinja2 # =================================== # classes/methods you want available # =================================== class MyClass( object ): def __init__(self): self.name = 'TestName' self.num = 1 def join_list( list ): return ','.join(list) # ================== # Add to environment # ================== env = jinja2.Environment( loader=jinja2.DictLoader({}) ) env.globals['join_list'] = join_list env.globals['MyClass'] = MyClass # =============== # Use in template # =============== template = env.from_string( 'hey this is {{ MyClass().name }}, check out list {{ join_list([1,2,3]) }}.' ) template.render() >>> 'hey this is TestName, check out list 3,2,1.'