OSDN Git Service

Regular updates
[twpd/master.git] / jinja.md
1 ---
2 title: Jinja
3 category: Python
4 layout: 2017/sheet
5 ---
6
7 {% raw %}
8 ### Basic usage
9
10 ```
11 - variable x has content: {{ x }}
12 - expression: {{ x + 1 }}
13 - escaped for HTML: {{ x | e }}
14 ```
15
16 ### Control structures
17
18 ```
19 {% for x in range(5) %}
20     {% if x % 2 == 0 %}
21         {{ x }} is even!
22     {% else %}
23         {{ x }} is odd!
24     {% endif %}
25 {% endfor %}
26 ```
27
28 ### Whitespace trimming
29
30 ```
31 these are
32 {{ "three" }}
33 lines.
34
35 this is conc
36 {{- "at" -}}
37 enated.
38 ```
39
40 ### Special blocks
41
42 ```
43 {% filter e %}{% endraw %}
44 { {%- if 0 -%}{%- endif -%} % raw %}
45 {%- raw -%}
46     This is a raw block where {{nothing is evaluated}}
47     {% not even this %}
48     and <html is escaped> too with "e" filter
49 {% endraw %}
50 { {%- if 0 -%}{%- endif -%} % endraw %}{% raw %}
51 {% endfilter %}
52
53 {% macro myfunc(x) %}
54     this is a reusable macro, with arguments: {{x}}
55 {% endmacro %}
56
57 {{ myfunc(42) }}
58
59 {#
60 this is a comment
61 #}
62 ```
63
64
65 ### Inheritance
66
67 #### shared.html
68
69 ```
70 <html>
71   <head>
72     <title>{%block title %}{% endblock %}</title>
73   </head>
74   <body>
75     <header><h1>{% block title %}{% endblock %}</h1></header>
76     <main>{% block content %}{% endblock %}</main>
77   </body>
78 </html>
79 ```
80
81 #### home.html
82
83 ```
84 {% extends "shared.html" %}
85 {% block title %}Welcome to my site{% endblock %}
86 {% block content %}
87 This is the body
88 {% endblock %}
89 ```
90
91 ## Library
92
93 ### Basic usage
94
95 ```python
96 from jinja2 import Template
97 template = Template('Hello {{ name }}!')
98 template.render(name='John Doe') == u'Hello John Doe!'
99 ```
100
101 {% endraw %}