HP-Handy
view release on metacpan or search on metacpan
doc/jinja2_cheatsheet.EN.txt view on Meta::CPAN
{% if x is none %} Value is undef (None)
{% if x is string %} Value is a non-reference scalar
{% if x is number %} Value is numeric
{% if x is sequence %} Value is an array reference
{% if x is mapping %} Value is a hash reference
{% if x is iterable %} Value is array or hash reference
{% if x is callable %} Value is a code reference
{% if n is odd %} Integer is odd
{% if n is even %} Integer is even
{% if n is divisibleby 3 %} Integer is divisible by N
{% if s is upper %} String is all uppercase
{% if s is lower %} String is all lowercase
{% if x is equalto y %} Value equals y
{% if x is not none %} Negation of test
[ 6. Conditional ]
{% if condition %}
...
{% elif other_condition %}
...
{% else %}
...
{% endif %}
Inline conditional (ternary):
{{ "yes" if flag else "no" }}
{{ value if value is defined else "default" }}
[ 7. For loop ]
{% for item in list %}
{{ loop.index }}: {{ item }}
{% endfor %}
Loop with else (shown when list is empty):
{% for item in list %}
{{ item }}
{% else %}
(no items)
{% endfor %}
Loop with filter:
{% for item in list if item != "" %}
{{ item }}
{% endfor %}
Dict iteration (key, value pairs sorted by key):
{% for key, value in mapping %}
{{ key }}: {{ value }}
{% endfor %}
loop special variable:
loop.index 1-based counter
loop.index0 0-based counter
loop.revindex reverse counter (1-based)
loop.revindex0 reverse counter (0-based)
loop.first true on first iteration
loop.last true on last iteration
loop.length total number of items
loop.odd true on odd-numbered iterations (1st, 3rd, ...)
loop.even true on even-numbered iterations (2nd, 4th, ...)
[ 8. Set ]
{% set x = 42 %}
{% set greeting = "Hello, " ~ name %}
{% set items = [1, 2, 3] %}
[ 9. Include ]
{% include "header.html" %}
{% include "optional.html" ignore missing %}
Variables from the calling template are accessible in the included file.
[ 10. Template inheritance ]
base.html:
<html>
<head><title>{% block title %}Default{% endblock %}</title></head>
<body>{% block content %}{% endblock %}</body>
</html>
child.html:
{% extends "base.html" %}
{% block title %}My Page{% endblock %}
{% block content %}<p>Hello</p>{% endblock %}
Note: HP::Handy supports single-level inheritance only.
super() (calling parent block content) is not supported.
[ 11. Macros ]
Define:
{% macro input(name, value="", type="text") %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
Call:
{{ input("username") }}
{{ input("password", type="password") }}
[ 12. With ]
{% with x = 10, y = 20 %}
{{ x + y }}
{% endwith %}
[ 13. Raw ]
{% raw %}
{{ this is not rendered }}
{% nor is this %}
{% endraw %}
[ 14. Expressions ]
Arithmetic: + - * / // % **
Concatenation: ~ (e.g. "Hello" ~ " " ~ name)
Comparison: == != < > <= >=
Logic: and or not
( run in 2.422 seconds using v1.01-cache-2.11-cpan-5c0b1e786e0 )