summaryrefslogtreecommitdiffhomepage
path: root/jinja.html.markdown
blob: 7e5b8e965454be630c86cbe4fab4d27d139ea4dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
---
language: Jinja
contributors:
  - ["AdaĆ­as Magdiel", "https://github.com/AdaiasMagdiel"]
filename: learn-jinja.j2
---

## Getting Started with Jinja

Jinja is a fast, expressive, and extensible templating engine for Python
applications.

Jinja includes a lot of functionalities, such as:
- Template inheritance and inclusion;
- Defining and importing macros within templates;
- Security mechanisms to prevent XSS attacks;
- A sandboxed environment that can safely render untrusted templates;
- Extensible filters, tests, functions, and even syntax.

A Jinja template is simply a text file. Jinja doesn't require a specific
extension, but it's common to use `.j2` or `.jinja` to make it easier for
some IDEs.

There are a few kinds of delimiters. The default Jinja delimiters are configured
as follows:

- `{% ... %}` for Statements
- `{{ ... }}` for Expressions to print to the template output
- `{# ... #}` for Comments not included in the template output

```jinja
{# This is an example of a comment. #}

{#
  You can use this syntax
  to write multiline comments
  as well.
#}
```


## VARIABLES

```jinja
{# You have the option to access variables from the context passed to the template #}

{{ foo }}

{# 
  Additionally, you can use a dot (.) to access attributes of a variable or
  use Python syntax, using []
#}

{{ foo.bar }}
{{ foo['bar'] }}

{# Within the template, you can define variables as well #}

{% set name = "Magdiel" %}
{{ name }}
```

## Loops

```html
<h1>Members</h1>
<ul>
{% for user in users %}
    <li>{{ user.username }}</li>
{% endfor %}
</ul>


<div>
{% for key, value in my_dict.items() %}
    <p>{{ key }}</p> - <p>{{ value }}</p>
{% endfor %}
</div>


<div>
{% for idx, url in enumerate(urls) %}
    <a href="{{ url }}">Go to url {{ idx + 1 }}</a>
{% endfor %}
</div>
```

## Conditionals

The if statement in Jinja is similar to the if statement in Python. It is
commonly used to check if a variable is defined, not empty, and not false in
its most basic form.

```html
{% if users %}
<ul>
{% for user in users %}
    <li>{{ user.username }}</li>
{% endfor %}
</ul>
{% endif %}


{# For multiple branches, elif and else can be used like in Python. #}


{% if message.status == "error" %}
    <p class="text-red-400">{{ message.content }}</p>
{% elif message.status == "success" %}
    <p class="text-green-400">{{ message.content }}</p>
{% else %}
    <p class="text-blue-400">{{ message.content }}</p>
{% endif %}
```

## Template Inheritance

One of the most powerful features of Jinja is template inheritance. You can
create a base layout with predefined blocks that you can extend in another file
and override with your own content.

```html
{# file: base.html.j2 #}

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock title %} - Learning Jinja</title>
    {% endblock head %}
</head>
<body>
    <main>
        {% block content %}{% endblock %}
        {# the endblock tag doesn't need the name of the block #}
    </main>
</body>
</html>



{# file: child.html.j2 #}

{% extends "base.html.j2" %}

{% block head %}
    {{ super() }}
    <script>
        console.log("There's a console.log here")
    </script>
{% endblock %}

{% block title %}Home{% endblock %}

{% block content %}
    <h1>Index</h1>
    <p>Welcome to my home homepage.</p>
{% endblock %}



{# RESULT #}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home - Learning Jinja</title>
    <script>
        console.log("There's a console.log here")
    </script>
</head>
<body>
    <main>
        <h1>Index</h1>
        <p>Welcome to my home homepage.</p>
    </main>
</body>
</html>

```

### Including Content

You can include content from another template on your current template using
the `{% include "template/path" %}` tag.

```html

{# file: footer.html.j2 #}

<footer>
    <p>&copy; 2024 - John Doe</p>
</footer>



{# file: index.html.j2 #}
...
<body>
    <main>
        <h1>Hi! I'm John Doe!</h1>
    </main>
    {% include "footer.html.j2" %}
</body>
...



{# RESULT #}

...
<body>
    <main>
        <h1>Hi! I'm John Doe!</h1>
    </main>
    <footer>
        <p>&copy; 2024 - John Doe</p>
    </footer>
</body>
...
```

Variables passed to the main template can also be used in the include, as the
included template has access to the context of the main template.

```html
{# file: greetings.html.j2 #}

<p>I'm the {{ name }} and i like to {{ hobby }}.</p>



{# file: index.html.j2 #}

{% set name = "Captain Nemo" %}
{% set hobby = "navigate through the depths of the ocean" %}

<div>
    {% include "greetings.html.j2" %}
</div>



{# RESULT #}

<div>
    <p>I'm the Captain Nemo and i like to navigate through the depths of the ocean.</p>
</div>
```

## Macros

Macros are basically like functions in another languages. You can define macros with or without arguments and reuse them in various parts of your template.

```html
{% macro input(value="", type="text", placeholder="") -%}
    <input type="{{ type }}" value="{{ value }}" placeholder="{{ placeholder }}">
{%- endmacro %}

<p>{{ input(placeholder="Your username") }}</p>
<p>{{ input(type="password") }}</p>
```

## Official Documentation

To learn more, access the [official documentation](https://jinja.palletsprojects.com/en/).