HP-Handy
view release on metacpan or search on metacpan
doc/jinja2_cheatsheet.EN.txt view on Meta::CPAN
{{ 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
Membership: in not in
Ternary: a if cond else b
Range: range(stop) range(start, stop) range(start, stop, step)
Literals: "string" 'string' 42 3.14 true false none [1,2,3]
[ 15. Custom filters and tests ]
# Register a custom filter
$tmpl->add_filter('rot13', sub {
my $s = $_[0];
$s =~ tr/A-Za-z/N-ZA-Mn-za-m/;
$s
});
# Usage: {{ text | rot13 }}
# Register a custom test
$tmpl->add_test('positive', sub { defined $_[0] && $_[0] > 0 });
# Usage: {% if n is positive %}
[ 16. Render methods ]
# From file (relative to template_dir)
my $html = $tmpl->render_file('index.html', \%vars);
# From string
my $html = $tmpl->render_string($source, \%vars);
[ 17. Official resources ]
Jinja2 documentation (Python reference):
https://jinja.palletsprojects.com/
( run in 1.119 second using v1.01-cache-2.11-cpan-40ba7b3775d )