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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
|
==================================
Built-in template tags and filters
==================================
This document describes Django's built-in template tags and filters. It is
recommended that you use the :doc:`automatic documentation
</ref/contrib/admin/admindocs>`, if available, as this will also include
documentation for any custom tags or filters installed.
.. _ref-templates-builtins-tags:
Built-in tag reference
======================
.. highlight:: html+django
.. templatetag:: autoescape
``autoescape``
--------------
Controls the current auto-escaping behavior. This tag takes either ``on`` or
``off`` as an argument and that determines whether auto-escaping is in effect
inside the block. The block is closed with an ``endautoescape`` ending tag.
When auto-escaping is in effect, all variable content has HTML escaping applied
to it before placing the result into the output (but after any filters have
been applied). This is equivalent to manually applying the :tfilter:`escape`
filter to each variable.
The only exceptions are variables that are already marked as "safe" from
escaping, either by the code that populated the variable, or because it has had
the :tfilter:`safe` or :tfilter:`escape` filters applied.
Sample usage::
{% autoescape on %}
{{ body }}
{% endautoescape %}
.. templatetag:: block
``block``
---------
Defines a block that can be overridden by child templates. See
:ref:`Template inheritance <template-inheritance>` for more information.
.. templatetag:: comment
``comment``
-----------
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
An optional note may be inserted in the first tag. For example, this is
useful when commenting out code for documenting why the code was disabled.
Sample usage::
<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
<p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}
``comment`` tags cannot be nested.
.. templatetag:: csrf_token
``csrf_token``
--------------
This tag is used for CSRF protection, as described in the documentation for
:doc:`Cross Site Request Forgeries </ref/csrf>`.
.. templatetag:: cycle
``cycle``
---------
Produces one of its arguments each time this tag is encountered. The first
argument is produced on the first encounter, the second argument on the second
encounter, and so forth. Once all arguments are exhausted, the tag cycles to
the first argument and produces it again.
This tag is particularly useful in a loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
The first iteration produces HTML that refers to class ``row1``, the second to
``row2``, the third to ``row1`` again, and so on for each iteration of the
loop.
You can use variables, too. For example, if you have two template variables,
``rowvalue1`` and ``rowvalue2``, you can alternate between their values like
this::
{% for o in some_list %}
<tr class="{% cycle rowvalue1 rowvalue2 %}">
...
</tr>
{% endfor %}
Variables included in the cycle will be escaped. You can disable auto-escaping
with::
{% for o in some_list %}
<tr class="{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}">
...
</tr>
{% endfor %}
You can mix variables and strings::
{% for o in some_list %}
<tr class="{% cycle 'row1' rowvalue2 'row3' %}">
...
</tr>
{% endfor %}
In some cases you might want to refer to the current value of a cycle
without advancing to the next value. To do this,
just give the ``{% cycle %}`` tag a name, using "as", like this::
{% cycle 'row1' 'row2' as rowcolors %}
From then on, you can insert the current value of the cycle wherever you'd like
in your template by referencing the cycle name as a context variable. If you
want to move the cycle to the next value independently of the original
``cycle`` tag, you can use another ``cycle`` tag and specify the name of the
variable. So, the following template::
<tr>
<td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
<td class="{{ rowcolors }}">...</td>
</tr>
<tr>
<td class="{% cycle rowcolors %}">...</td>
<td class="{{ rowcolors }}">...</td>
</tr>
would output::
<tr>
<td class="row1">...</td>
<td class="row1">...</td>
</tr>
<tr>
<td class="row2">...</td>
<td class="row2">...</td>
</tr>
You can use any number of values in a ``cycle`` tag, separated by spaces.
Values enclosed in single quotes (``'``) or double quotes (``"``) are treated
as string literals, while values without quotes are treated as template
variables.
By default, when you use the ``as`` keyword with the cycle tag, the
usage of ``{% cycle %}`` that initiates the cycle will itself produce
the first value in the cycle. This could be a problem if you want to
use the value in a nested loop or an included template. If you only want
to declare the cycle but not produce the first value, you can add a
``silent`` keyword as the last keyword in the tag. For example::
{% for obj in some_list %}
{% cycle 'row1' 'row2' as rowcolors silent %}
<tr class="{{ rowcolors }}">{% include "subtemplate.html" %}</tr>
{% endfor %}
This will output a list of ``<tr>`` elements with ``class``
alternating between ``row1`` and ``row2``. The subtemplate will have
access to ``rowcolors`` in its context and the value will match the class
of the ``<tr>`` that encloses it. If the ``silent`` keyword were to be
omitted, ``row1`` and ``row2`` would be emitted as normal text, outside the
``<tr>`` element.
When the silent keyword is used on a cycle definition, the silence
automatically applies to all subsequent uses of that specific cycle tag.
The following template would output *nothing*, even though the second
call to ``{% cycle %}`` doesn't specify ``silent``::
{% cycle 'row1' 'row2' as rowcolors silent %}
{% cycle rowcolors %}
You can use the :ttag:`resetcycle` tag to make a ``{% cycle %}`` tag restart
from its first value when it's next encountered.
.. templatetag:: debug
``debug``
---------
Outputs a whole load of debugging information, including the current context
and imported modules.
.. templatetag:: extends
``extends``
-----------
Signals that this template extends a parent template.
This tag can be used in two ways:
* ``{% extends "base.html" %}`` (with quotes) uses the literal value
``"base.html"`` as the name of the parent template to extend.
* ``{% extends variable %}`` uses the value of ``variable``. If the variable
evaluates to a string, Django will use that string as the name of the
parent template. If the variable evaluates to a ``Template`` object,
Django will use that object as the parent template.
See :ref:`template-inheritance` for more information.
Normally the template name is relative to the template loader's root directory.
A string argument may also be a relative path starting with ``./`` or ``../``.
For example, assume the following directory structure::
dir1/
template.html
base2.html
my/
base3.html
base1.html
In ``template.html``, the following paths would be valid::
{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}
.. templatetag:: filter
``filter``
----------
Filters the contents of the block through one or more filters. Multiple
filters can be specified with pipes and filters can have arguments, just as
in variable syntax.
Note that the block includes *all* the text between the ``filter`` and
``endfilter`` tags.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in all lowercase.
{% endfilter %}
.. note::
The :tfilter:`escape` and :tfilter:`safe` filters are not acceptable
arguments. Instead, use the :ttag:`autoescape` tag to manage autoescaping
for blocks of template code.
.. templatetag:: firstof
``firstof``
-----------
Outputs the first argument variable that is not ``False``. Outputs nothing if
all the passed variables are ``False``.
Sample usage::
{% firstof var1 var2 var3 %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
You can also use a literal string as a fallback value in case all
passed variables are False::
{% firstof var1 var2 var3 "fallback value" %}
This tag auto-escapes variable values. You can disable auto-escaping with::
{% autoescape off %}
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% endautoescape %}
Or if only some variables should be escaped, you can use::
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
You can use the syntax ``{% firstof var1 var2 var3 as value %}`` to store the
output inside a variable.
.. templatetag:: for
``for``
-------
Loops over each item in an array, making the item available in a context
variable. For example, to display a list of athletes provided in
``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by using
``{% for obj in list reversed %}``.
If you need to loop over a list of lists, you can unpack the values
in each sublist into individual variables. For example, if your context
contains a list of (x,y) coordinates called ``points``, you could use the
following to output the list of points::
{% for x, y in points %}
There is a point at {{ x }},{{ y }}
{% endfor %}
This can also be useful if you need to access the items in a dictionary.
For example, if your context contained a dictionary ``data``, the following
would display the keys and values of the dictionary::
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
Keep in mind that for the dot operator, dictionary key lookup takes precedence
over method lookup. Therefore if the ``data`` dictionary contains a key named
``'items'``, ``data.items`` will return ``data['items']`` instead of
``data.items()``. Avoid adding keys that are named like dictionary methods if
you want to use those methods in a template (``items``, ``values``, ``keys``,
etc.). Read more about the lookup order of the dot operator in the
:ref:`documentation of template variables <template-variables>`.
The for loop sets a number of variables available within the loop:
========================== ===============================================
Variable Description
========================== ===============================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop surrounding
the current one
========================== ===============================================
``for`` ... ``empty``
---------------------
The ``for`` tag can take an optional ``{% empty %}`` clause whose text is
displayed if the given array is empty or could not be found::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::
<ul>
{% if athlete_list %}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{% else %}
<li>Sorry, no athletes in this list.</li>
{% endif %}
</ul>
.. templatetag:: if
``if``
------
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
exists, is not empty, and is not a false boolean value) the contents of the
block are output::
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes will be
displayed by the ``{{ athlete_list|length }}`` variable.
As you can see, the ``if`` tag may take one or several ``{% elif %}``
clauses, as well as an ``{% else %}`` clause that will be displayed if all
previous conditions fail. These clauses are optional.
Boolean operators
~~~~~~~~~~~~~~~~~
:ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of
variables or to negate a given variable::
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
Use of both ``and`` and ``or`` clauses within the same tag is allowed, with
``and`` having higher precedence than ``or`` e.g.::
{% if athlete_list and coach_list or cheerleader_list %}
will be interpreted like:
.. code-block:: python
if (athlete_list and coach_list) or cheerleader_list
Use of actual parentheses in the :ttag:`if` tag is invalid syntax. If you need
them to indicate precedence, you should use nested :ttag:`if` tags.
:ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
``<=``, ``>=``, ``in``, ``not in``, ``is``, and ``is not`` which work as
follows:
``==`` operator
^^^^^^^^^^^^^^^
Equality. Example::
{% if somevar == "x" %}
This appears if variable somevar equals the string "x"
{% endif %}
``!=`` operator
^^^^^^^^^^^^^^^
Inequality. Example::
{% if somevar != "x" %}
This appears if variable somevar does not equal the string "x",
or if somevar is not found in the context
{% endif %}
``<`` operator
^^^^^^^^^^^^^^
Less than. Example::
{% if somevar < 100 %}
This appears if variable somevar is less than 100.
{% endif %}
``>`` operator
^^^^^^^^^^^^^^
Greater than. Example::
{% if somevar > 0 %}
This appears if variable somevar is greater than 0.
{% endif %}
``<=`` operator
^^^^^^^^^^^^^^^
Less than or equal to. Example::
{% if somevar <= 100 %}
This appears if variable somevar is less than 100 or equal to 100.
{% endif %}
``>=`` operator
^^^^^^^^^^^^^^^
Greater than or equal to. Example::
{% if somevar >= 1 %}
This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
``in`` operator
^^^^^^^^^^^^^^^
Contained within. This operator is supported by many Python containers to test
whether the given value is in the container. The following are some examples
of how ``x in y`` will be interpreted::
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
{% endif %}
{% if "hello" in greetings %}
If greetings is a list or set, one element of which is the string
"hello", this will appear.
{% endif %}
{% if user in users %}
If users is a QuerySet, this will appear if user is an
instance that belongs to the QuerySet.
{% endif %}
``not in`` operator
^^^^^^^^^^^^^^^^^^^
Not contained within. This is the negation of the ``in`` operator.
``is`` operator
^^^^^^^^^^^^^^^
Object identity. Tests if two values are the same object. Example::
{% if somevar is True %}
This appears if and only if somevar is True.
{% endif %}
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
``is not`` operator
^^^^^^^^^^^^^^^^^^^
Negated object identity. Tests if two values are not the same object. This is
the negation of the ``is`` operator. Example::
{% if somevar is not True %}
This appears if somevar is not True, or if somevar is not found in the
context.
{% endif %}
{% if somevar is not None %}
This appears if and only if somevar is not None.
{% endif %}
Filters
~~~~~~~
You can also use filters in the :ttag:`if` expression. For example::
{% if messages|length >= 100 %}
You have lots of messages today!
{% endif %}
Complex expressions
~~~~~~~~~~~~~~~~~~~
All of the above can be combined to form complex expressions. For such
expressions, it can be important to know how the operators are grouped when the
expression is evaluated - that is, the precedence rules. The precedence of the
operators, from lowest to highest, is as follows:
* ``or``
* ``and``
* ``not``
* ``in``
* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``
(This follows Python exactly). So, for example, the following complex
:ttag:`if` tag::
{% if a == b or c == d and e %}
...will be interpreted as:
.. code-block:: python
(a == b) or ((c == d) and e)
If you need different precedence, you will need to use nested :ttag:`if` tags.
Sometimes that is better for clarity anyway, for the sake of those who do not
know the precedence rules.
The comparison operators cannot be 'chained' like in Python or in mathematical
notation. For example, instead of using::
{% if a > b > c %} (WRONG)
you should use::
{% if a > b and b > c %}
``ifequal`` and ``ifnotequal``
------------------------------
``{% ifequal a b %} ... {% endifequal %}`` is an obsolete way to write
``{% if a == b %} ... {% endif %}``. Likewise, ``{% ifnotequal a b %} ...
{% endifnotequal %}`` is superseded by ``{% if a != b %} ... {% endif %}``.
The ``ifequal`` and ``ifnotequal`` tags will be deprecated in a future release.
.. templatetag:: ifchanged
``ifchanged``
-------------
Check if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two possible
uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a list of
days, only displaying the month if it changes::
<h1>Archive for {{ year }}</h1>
{% for date in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{% endfor %}
2. If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
showing the hour if either the hour or the date has changed::
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
will be displayed if the value has not changed::
{% for match in matches %}
<div style="background-color:
{% ifchanged match.ballot_id %}
{% cycle "red" "blue" %}
{% else %}
gray
{% endifchanged %}
">{{ match }}</div>
{% endfor %}
.. templatetag:: include
``include``
-----------
Loads a template and renders it with the current context. This is a way of
"including" other templates within a template.
The template name can either be a variable or a hard-coded (quoted) string,
in either single or double quotes.
This example includes the contents of the template ``"foo/bar.html"``::
{% include "foo/bar.html" %}
Normally the template name is relative to the template loader's root directory.
A string argument may also be a relative path starting with ``./`` or ``../``
as described in the :ttag:`extends` tag.
This example includes the contents of the template whose name is contained in
the variable ``template_name``::
{% include template_name %}
The variable may also be any object with a ``render()`` method that accepts a
context. This allows you to reference a compiled ``Template`` in your context.
An included template is rendered within the context of the template that
includes it. This example produces the output ``"Hello, John!"``:
* Context: variable ``person`` is set to ``"John"`` and variable ``greeting``
is set to ``"Hello"``.
* Template::
{% include "name_snippet.html" %}
* The ``name_snippet.html`` template::
{{ greeting }}, {{ person|default:"friend" }}!
You can pass additional context to the template using keyword arguments::
{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
If you want to render the context only with the variables provided (or even
no variables at all), use the ``only`` option. No other variables are
available to the included template::
{% include "name_snippet.html" with greeting="Hi" only %}
.. note::
The :ttag:`include` tag should be considered as an implementation of
"render this subtemplate and include the HTML", not as "parse this
subtemplate and include its contents as if it were part of the parent".
This means that there is no shared state between included templates --
each include is a completely independent rendering process.
Blocks are evaluated *before* they are included. This means that a template
that includes blocks from another will contain blocks that have *already
been evaluated and rendered* - not blocks that can be overridden by, for
example, an extending template.
.. templatetag:: load
``load``
--------
Loads a custom template tag set.
For example, the following template would load all the tags and filters
registered in ``somelibrary`` and ``otherlibrary`` located in package
``package``::
{% load somelibrary package.otherlibrary %}
You can also selectively load individual filters or tags from a library, using
the ``from`` argument. In this example, the template tags/filters named ``foo``
and ``bar`` will be loaded from ``somelibrary``::
{% load foo bar from somelibrary %}
See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for
more information.
.. templatetag:: lorem
``lorem``
---------
Displays random "lorem ipsum" Latin text. This is useful for providing sample
data in templates.
Usage::
{% lorem [count] [method] [random] %}
The ``{% lorem %}`` tag can be used with zero, one, two or three arguments.
The arguments are:
=========== =============================================================
Argument Description
=========== =============================================================
``count`` A number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` Either ``w`` for words, ``p`` for HTML paragraphs or ``b``
for plain-text paragraph blocks (default is ``b``).
``random`` The word ``random``, which if given, does not use the common
paragraph ("Lorem ipsum dolor sit amet...") when generating
text.
=========== =============================================================
Examples:
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph.
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
and two random paragraphs each wrapped in HTML ``<p>`` tags.
* ``{% lorem 2 w random %}`` will output two random Latin words.
.. templatetag:: now
``now``
-------
Displays the current date and/or time, using a format according to the given
string. Such string can contain format specifiers characters as described
in the :tfilter:`date` filter section.
Example::
It is {% now "jS F Y H:i" %}
Note that you can backslash-escape a format string if you want to use the
"raw" value. In this example, both "o" and "f" are backslash-escaped, because
otherwise each is a format string that displays the year and the time,
respectively::
It is the {% now "jS \o\f F" %}
This would display as "It is the 4th of September".
.. note::
The format passed can also be one of the predefined ones
:setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`,
:setting:`SHORT_DATE_FORMAT` or :setting:`SHORT_DATETIME_FORMAT`.
The predefined formats may vary depending on the current locale and
if :doc:`/topics/i18n/formatting` is enabled, e.g.::
It is {% now "SHORT_DATETIME_FORMAT" %}
You can also use the syntax ``{% now "Y" as current_year %}`` to store the
output (as a string) inside a variable. This is useful if you want to use
``{% now %}`` inside a template tag like :ttag:`blocktrans` for example::
{% now "Y" as current_year %}
{% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}
.. templatetag:: regroup
``regroup``
-----------
Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by way of an example: say that ``cities``
is a list of cities represented by dictionaries containing ``"name"``,
``"population"``, and ``"country"`` keys:
.. code-block:: python
cities = [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
...and you'd like to display a hierarchical list that is ordered by country,
like this:
* India
* Mumbai: 19,000,000
* Calcutta: 15,000,000
* USA
* New York: 20,000,000
* Chicago: 7,000,000
* Japan
* Tokyo: 33,000,000
You can use the ``{% regroup %}`` tag to group the list of cities by country.
The following snippet of template code would accomplish this::
{% regroup cities by country as country_list %}
<ul>
{% for country in country_list %}
<li>{{ country.grouper }}
<ul>
{% for city in country.list %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Let's walk through this example. ``{% regroup %}`` takes three arguments: the
list you want to regroup, the attribute to group by, and the name of the
resulting list. Here, we're regrouping the ``cities`` list by the ``country``
attribute and calling the result ``country_list``.
``{% regroup %}`` produces a list (in this case, ``country_list``) of
**group objects**. Group objects are instances of
:py:func:`~collections.namedtuple` with two fields:
* ``grouper`` -- the item that was grouped by (e.g., the string "India" or
"Japan").
* ``list`` -- a list of all items in this group (e.g., a list of all cities
with country='India').
Because ``{% regroup %}`` produces :py:func:`~collections.namedtuple` objects,
you can also write the previous example as::
{% regroup cities by country as country_list %}
<ul>
{% for country, local_cities in country_list %}
<li>{{ country }}
<ul>
{% for city in local_cities %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Note that ``{% regroup %}`` does not order its input! Our example relies on
the fact that the ``cities`` list was ordered by ``country`` in the first place.
If the ``cities`` list did *not* order its members by ``country``, the
regrouping would naively display more than one group for a single country. For
example, say the ``cities`` list was set to this (note that the countries are not
grouped together):
.. code-block:: python
cities = [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
With this input for ``cities``, the example ``{% regroup %}`` template code
above would result in the following output:
* India
* Mumbai: 19,000,000
* USA
* New York: 20,000,000
* India
* Calcutta: 15,000,000
* USA
* Chicago: 7,000,000
* Japan
* Tokyo: 33,000,000
The easiest solution to this gotcha is to make sure in your view code that the
data is ordered according to how you want to display it.
Another solution is to sort the data in the template using the
:tfilter:`dictsort` filter, if your data is in a list of dictionaries::
{% regroup cities|dictsort:"country" by country as country_list %}
Grouping on other properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Any valid template lookup is a legal grouping attribute for the regroup
tag, including methods, attributes, dictionary keys and list items. For
example, if the "country" field is a foreign key to a class with
an attribute "description," you could use::
{% regroup cities by country.description as country_list %}
Or, if ``country`` is a field with ``choices``, it will have a
:meth:`~django.db.models.Model.get_FOO_display` method available as an
attribute, allowing you to group on the display string rather than the
``choices`` key::
{% regroup cities by get_country_display as country_list %}
``{{ country.grouper }}`` will now display the value fields from the
``choices`` set rather than the keys.
.. templatetag:: resetcycle
``resetcycle``
--------------
Resets a previous `cycle`_ so that it restarts from its first item at its next
encounter. Without arguments, ``{% resetcycle %}`` will reset the last
``{% cycle %}`` defined in the template.
Example usage::
{% for coach in coach_list %}
<h1>{{ coach.name }}</h1>
{% for athlete in coach.athlete_set.all %}
<p class="{% cycle 'odd' 'even' %}">{{ athlete.name }}</p>
{% endfor %}
{% resetcycle %}
{% endfor %}
This example would return this HTML::
<h1>José Mourinho</h1>
<p class="odd">Thibaut Courtois</p>
<p class="even">John Terry</p>
<p class="odd">Eden Hazard</p>
<h1>Carlo Ancelotti</h1>
<p class="odd">Manuel Neuer</p>
<p class="even">Thomas Müller</p>
Notice how the first block ends with ``class="odd"`` and the new one starts
with ``class="odd"``. Without the ``{% resetcycle %}`` tag, the second block
would start with ``class="even"``.
You can also reset named cycle tags::
{% for item in list %}
<p class="{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}">
{{ item.data }}
</p>
{% ifchanged item.category %}
<h1>{{ item.category }}</h1>
{% if not forloop.first %}{% resetcycle tick %}{% endif %}
{% endifchanged %}
{% endfor %}
In this example, we have both the alternating odd/even rows and a "major" row
every fifth row. Only the five-row cycle is reset when a category changes.
.. templatetag:: spaceless
``spaceless``
-------------
Removes whitespace between HTML tags. This includes tab
characters and newlines.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example would return this HTML::
<p><a href="foo/">Foo</a></p>
Only space between *tags* is removed -- not space between tags and text. In
this example, the space around ``Hello`` won't be stripped::
{% spaceless %}
<strong>
Hello
</strong>
{% endspaceless %}
.. templatetag:: templatetag
``templatetag``
---------------
Outputs one of the syntax characters used to compose template tags.
Since the template system has no concept of "escaping", to display one of the
bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
================== =======
Argument Outputs
================== =======
``openblock`` ``{%``
``closeblock`` ``%}``
``openvariable`` ``{{``
``closevariable`` ``}}``
``openbrace`` ``{``
``closebrace`` ``}``
``opencomment`` ``{#``
``closecomment`` ``#}``
================== =======
Sample usage::
{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}
.. templatetag:: url
``url``
-------
Returns an absolute path reference (a URL without the domain name) matching a
given view and optional parameters. Any special characters in the resulting
path will be encoded using :func:`~django.utils.encoding.iri_to_uri`.
This is a way to output links without violating the DRY principle by having to
hard-code URLs in your templates::
{% url 'some-url-name' v1 v2 %}
The first argument is a :ref:`URL pattern name <naming-url-patterns>`. It can
be a quoted literal or any other context variable. Additional arguments are
optional and should be space-separated values that will be used as arguments in
the URL. The example above shows passing positional arguments. Alternatively
you may use keyword syntax::
{% url 'some-url-name' arg1=v1 arg2=v2 %}
Do not mix both positional and keyword syntax in a single call. All arguments
required by the URLconf should be present.
For example, suppose you have a view, ``app_views.client``, whose URLconf
takes a client ID (here, ``client()`` is a method inside the views file
``app_views.py``). The URLconf line might look like this:
.. code-block:: python
path('client/<int:id>/', app_views.client, name='app-views-client')
If this app's URLconf is included into the project's URLconf under a path
such as this:
.. code-block:: python
path('clients/', include('project_name.app_name.urls'))
...then, in a template, you can create a link to this view like this::
{% url 'app-views-client' client.id %}
The template tag will output the string ``/clients/client/123/``.
Note that if the URL you're reversing doesn't exist, you'll get an
:exc:`~django.urls.NoReverseMatch` exception raised, which will cause your
site to display an error page.
If you'd like to retrieve a URL without displaying it, you can use a slightly
different call::
{% url 'some-url-name' arg arg2 as the_url %}
<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
The scope of the variable created by the ``as var`` syntax is the
``{% block %}`` in which the ``{% url %}`` tag appears.
This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
missing. In practice you'll use this to link to views that are optional::
{% url 'some-url-name' as the_url %}
{% if the_url %}
<a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}
If you'd like to retrieve a namespaced URL, specify the fully qualified name::
{% url 'myapp:view-name' %}
This will follow the normal :ref:`namespaced URL resolution strategy
<topics-http-reversing-url-namespaces>`, including using any hints provided
by the context as to the current application.
.. warning::
Don't forget to put quotes around the URL pattern ``name``, otherwise the
value will be interpreted as a context variable!
.. templatetag:: verbatim
``verbatim``
------------
Stops the template engine from rendering the contents of this block tag.
A common use is to allow a JavaScript template layer that collides with
Django's syntax. For example::
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
You can also designate a specific closing tag, allowing the use of
``{% endverbatim %}`` as part of the unrendered contents::
{% verbatim myblock %}
Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}
.. templatetag:: widthratio
``widthratio``
--------------
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}">
If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100, the
image in the above example will be 88 pixels wide
(because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
In some cases you might want to capture the result of ``widthratio`` in a
variable. It can be useful, for instance, in a :ttag:`blocktrans` like this::
{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}
.. templatetag:: with
``with``
--------
Caches a complex variable under a simpler name. This is useful when accessing
an "expensive" method (e.g., one that hits the database) multiple times.
For example::
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
The populated variable (in the example above, ``total``) is only available
between the ``{% with %}`` and ``{% endwith %}`` tags.
You can assign more than one context variable::
{% with alpha=1 beta=2 %}
...
{% endwith %}
.. note:: The previous more verbose format is still supported:
``{% with business.employees.count as total %}``
.. _ref-templates-builtins-filters:
Built-in filter reference
=========================
.. templatefilter:: add
``add``
-------
Adds the argument to the value.
For example::
{{ value|add:"2" }}
If ``value`` is ``4``, then the output will be ``6``.
This filter will first try to coerce both values to integers. If this fails,
it'll attempt to add the values together anyway. This will work on some data
types (strings, list, etc.) and fail on others. If it fails, the result will
be an empty string.
For example, if we have::
{{ first|add:second }}
and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the
output will be ``[1, 2, 3, 4, 5, 6]``.
.. warning::
Strings that can be coerced to integers will be **summed**, not
concatenated, as in the first example above.
.. templatefilter:: addslashes
``addslashes``
--------------
Adds slashes before quotes. Useful for escaping strings in CSV, for example.
For example::
{{ value|addslashes }}
If ``value`` is ``"I'm using Django"``, the output will be
``"I\'m using Django"``.
.. templatefilter:: capfirst
``capfirst``
------------
Capitalizes the first character of the value. If the first character is not
a letter, this filter has no effect.
For example::
{{ value|capfirst }}
If ``value`` is ``"django"``, the output will be ``"Django"``.
.. templatefilter:: center
``center``
----------
Centers the value in a field of a given width.
For example::
"{{ value|center:"15" }}"
If ``value`` is ``"Django"``, the output will be ``" Django "``.
.. templatefilter:: cut
``cut``
-------
Removes all values of arg from the given string.
For example::
{{ value|cut:" " }}
If ``value`` is ``"String with spaces"``, the output will be
``"Stringwithspaces"``.
.. templatefilter:: date
``date``
--------
Formats a date according to the given format.
Uses a similar format as PHP's ``date()`` function (https://php.net/date)
with some differences.
.. note::
These format characters are not used in Django outside of templates. They
were designed to be compatible with PHP to ease transitioning for designers.
.. _date-and-time-formatting-specifiers:
Available format strings:
================ ======================================== =====================
Format character Description Example output
================ ======================================== =====================
**Day**
``d`` Day of the month, 2 digits with ``'01'`` to ``'31'``
leading zeros.
``j`` Day of the month without leading ``'1'`` to ``'31'``
zeros.
``D`` Day of the week, textual, 3 letters. ``'Fri'``
``l`` Day of the week, textual, long. ``'Friday'``
``S`` English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
month, 2 characters.
``w`` Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
leading zeros.
``z`` Day of the year. ``1`` to ``366``
**Week**
``W`` ISO-8601 week number of year, with ``1``, ``53``
weeks starting on Monday.
**Month**
``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
``n`` Month without leading zeros. ``'1'`` to ``'12'``
``M`` Month, textual, 3 letters. ``'Jan'``
``b`` Month, textual, 3 letters, lowercase. ``'jan'``
``E`` Month, locale specific alternative
representation usually used for long
date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)
``F`` Month, textual, long. ``'January'``
``N`` Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
style. Proprietary extension.
``t`` Number of days in the given month. ``28`` to ``31``
**Year**
``y`` Year, 2 digits. ``'99'``
``Y`` Year, 4 digits. ``'1999'``
``L`` Boolean for whether it's a leap year. ``True`` or ``False``
``o`` ISO-8601 week-numbering year, ``'1999'``
corresponding to the ISO-8601 week
number (W) which uses leap weeks. See Y
for the more common year format.
**Time**
``g`` Hour, 12-hour format without leading ``'1'`` to ``'12'``
zeros.
``G`` Hour, 24-hour format without leading ``'0'`` to ``'23'``
zeros.
``h`` Hour, 12-hour format. ``'01'`` to ``'12'``
``H`` Hour, 24-hour format. ``'00'`` to ``'23'``
``i`` Minutes. ``'00'`` to ``'59'``
``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
``u`` Microseconds. ``000000`` to ``999999``
``a`` ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
this is slightly different than PHP's
output, because this includes periods
to match Associated Press style.)
``A`` ``'AM'`` or ``'PM'``. ``'AM'``
``f`` Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
with minutes left off if they're zero.
Proprietary extension.
``P`` Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
'a.m.'/'p.m.', with minutes left off
if they're zero and the special-case
strings 'midnight' and 'noon' if
appropriate. Proprietary extension.
**Timezone**
``e`` Timezone name. Could be in any format,
or might return an empty string, ``''``, ``'GMT'``, ``'-500'``, ``'US/Eastern'``, etc.
depending on the datetime.
``I`` Daylight Savings Time, whether it's ``'1'`` or ``'0'``
in effect or not.
``O`` Difference to Greenwich time in hours. ``'+0200'``
``T`` Time zone of this machine. ``'EST'``, ``'MDT'``
``Z`` Time zone offset in seconds. The ``-43200`` to ``43200``
offset for timezones west of UTC is
always negative, and for those east of
UTC is always positive.
**Date/Time**
``c`` ISO 8601 format. (Note: unlike others ``2008-01-02T10:30:00.000123+02:00``,
formatters, such as "Z", "O" or "r", or ``2008-01-02T10:30:00.000123`` if the datetime is naive
the "c" formatter will not add timezone
offset if value is a naive datetime
(see :class:`datetime.tzinfo`).
``r`` :rfc:`5322` formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
``U`` Seconds since the Unix Epoch
(January 1 1970 00:00:00 UTC).
================ ======================================== =====================
For example::
{{ value|date:"D d M Y" }}
If ``value`` is a :py:class:`~datetime.datetime` object (e.g., the result of
``datetime.datetime.now()``), the output will be the string
``'Wed 09 Jan 2008'``.
The format passed can be one of the predefined ones :setting:`DATE_FORMAT`,
:setting:`DATETIME_FORMAT`, :setting:`SHORT_DATE_FORMAT` or
:setting:`SHORT_DATETIME_FORMAT`, or a custom format that uses the format
specifiers shown in the table above. Note that predefined formats may vary
depending on the current locale.
Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
for example, ``"es"``, then for::
{{ value|date:"SHORT_DATE_FORMAT" }}
the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"``
format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``).
When used without a format string, the ``DATE_FORMAT`` format specifier is
used. Assuming the same settings as the previous example::
{{ value|date }}
outputs ``9 de Enero de 2008`` (the ``DATE_FORMAT`` format specifier for the
``es`` locale is ``r'j \d\e F \d\e Y'``.
You can combine ``date`` with the :tfilter:`time` filter to render a full
representation of a ``datetime`` value. E.g.::
{{ value|date:"D d M Y" }} {{ value|time:"H:i" }}
.. templatefilter:: default
``default``
-----------
If value evaluates to ``False``, uses the given default. Otherwise, uses the
value.
For example::
{{ value|default:"nothing" }}
If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
.. templatefilter:: default_if_none
``default_if_none``
-------------------
If (and only if) value is ``None``, uses the given default. Otherwise, uses the
value.
Note that if an empty string is given, the default value will *not* be used.
Use the :tfilter:`default` filter if you want to fallback for empty strings.
For example::
{{ value|default_if_none:"nothing" }}
If ``value`` is ``None``, the output will be ``nothing``.
.. templatefilter:: dictsort
``dictsort``
------------
Takes a list of dictionaries and returns that list sorted by the key given in
the argument.
For example::
{{ value|dictsort:"name" }}
If ``value`` is:
.. code-block:: python
[
{'name': 'zed', 'age': 19},
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
]
then the output would be:
.. code-block:: python
[
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
{'name': 'zed', 'age': 19},
]
You can also do more complicated things like::
{% for book in books|dictsort:"author.age" %}
* {{ book.title }} ({{ book.author.name }})
{% endfor %}
If ``books`` is:
.. code-block:: python
[
{'title': '1984', 'author': {'name': 'George', 'age': 45}},
{'title': 'Timequake', 'author': {'name': 'Kurt', 'age': 75}},
{'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},
]
then the output would be::
* Alice (Lewis)
* 1984 (George)
* Timequake (Kurt)
``dictsort`` can also order a list of lists (or any other object implementing
``__getitem__()``) by elements at specified index. For example::
{{ value|dictsort:0 }}
If ``value`` is:
.. code-block:: python
[
('a', '42'),
('c', 'string'),
('b', 'foo'),
]
then the output would be:
.. code-block:: python
[
('a', '42'),
('b', 'foo'),
('c', 'string'),
]
You must pass the index as an integer rather than a string. The following
produce empty output::
{{ values|dictsort:"0" }}
.. templatefilter:: dictsortreversed
``dictsortreversed``
--------------------
Takes a list of dictionaries and returns that list sorted in reverse order by
the key given in the argument. This works exactly the same as the above filter,
but the returned value will be in reverse order.
.. templatefilter:: divisibleby
``divisibleby``
---------------
Returns ``True`` if the value is divisible by the argument.
For example::
{{ value|divisibleby:"3" }}
If ``value`` is ``21``, the output would be ``True``.
.. templatefilter:: escape
``escape``
----------
Escapes a string's HTML. Specifically, it makes these replacements:
* ``<`` is converted to ``<``
* ``>`` is converted to ``>``
* ``'`` (single quote) is converted to ``'``
* ``"`` (double quote) is converted to ``"``
* ``&`` is converted to ``&``
Applying ``escape`` to a variable that would normally have auto-escaping
applied to the result will only result in one round of escaping being done. So
it is safe to use this function even in auto-escaping environments. If you want
multiple escaping passes to be applied, use the :tfilter:`force_escape` filter.
For example, you can apply ``escape`` to fields when :ttag:`autoescape` is off::
{% autoescape off %}
{{ title|escape }}
{% endautoescape %}
.. templatefilter:: escapejs
``escapejs``
------------
Escapes characters for use in JavaScript strings. This does *not* make the
string safe for use in HTML or JavaScript template literals, but does protect
you from syntax errors when using templates to generate JavaScript/JSON.
For example::
{{ value|escapejs }}
If ``value`` is ``"testing\r\njavascript \'string" <b>escaping</b>"``,
the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"``.
.. templatefilter:: filesizeformat
``filesizeformat``
------------------
Formats the value like a 'human-readable' file size (i.e. ``'13 KB'``,
``'4.1 MB'``, ``'102 bytes'``, etc.).
For example::
{{ value|filesizeformat }}
If ``value`` is 123456789, the output would be ``117.7 MB``.
.. admonition:: File sizes and SI units
Strictly speaking, ``filesizeformat`` does not conform to the International
System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes
are calculated in powers of 1024 (which is the case here). Instead, Django
uses traditional unit names (KB, MB, GB, etc.) corresponding to names that
are more commonly used.
.. templatefilter:: first
``first``
---------
Returns the first item in a list.
For example::
{{ value|first }}
If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
.. templatefilter:: floatformat
``floatformat``
---------------
When used without an argument, rounds a floating-point number to one decimal
place -- but only if there's a decimal part to be displayed. For example:
============ =========================== ========
``value`` Template Output
============ =========================== ========
``34.23234`` ``{{ value|floatformat }}`` ``34.2``
``34.00000`` ``{{ value|floatformat }}`` ``34``
``34.26000`` ``{{ value|floatformat }}`` ``34.3``
============ =========================== ========
If used with a numeric integer argument, ``floatformat`` rounds a number to
that many decimal places. For example:
============ ============================= ==========
``value`` Template Output
============ ============================= ==========
``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232``
``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000``
``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260``
============ ============================= ==========
Particularly useful is passing 0 (zero) as the argument which will round the
float to the nearest integer.
============ ================================ ==========
``value`` Template Output
============ ================================ ==========
``34.23234`` ``{{ value|floatformat:"0" }}`` ``34``
``34.00000`` ``{{ value|floatformat:"0" }}`` ``34``
``39.56000`` ``{{ value|floatformat:"0" }}`` ``40``
============ ================================ ==========
If the argument passed to ``floatformat`` is negative, it will round a number
to that many decimal places -- but only if there's a decimal part to be
displayed. For example:
============ ================================ ==========
``value`` Template Output
============ ================================ ==========
``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232``
``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34``
``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260``
============ ================================ ==========
Using ``floatformat`` with no argument is equivalent to using ``floatformat``
with an argument of ``-1``.
.. templatefilter:: force_escape
``force_escape``
----------------
Applies HTML escaping to a string (see the :tfilter:`escape` filter for
details). This filter is applied *immediately* and returns a new, escaped
string. This is useful in the rare cases where you need multiple escaping or
want to apply other filters to the escaped results. Normally, you want to use
the :tfilter:`escape` filter.
For example, if you want to catch the ``<p>`` HTML elements created by
the :tfilter:`linebreaks` filter::
{% autoescape off %}
{{ body|linebreaks|force_escape }}
{% endautoescape %}
.. templatefilter:: get_digit
``get_digit``
-------------
Given a whole number, returns the requested digit, where 1 is the right-most
digit, 2 is the second-right-most digit, etc. Returns the original value for
invalid input (if input or argument is not an integer, or if argument is less
than 1). Otherwise, output is always an integer.
For example::
{{ value|get_digit:"2" }}
If ``value`` is ``123456789``, the output will be ``8``.
.. templatefilter:: iriencode
``iriencode``
-------------
Converts an IRI (Internationalized Resource Identifier) to a string that is
suitable for including in a URL. This is necessary if you're trying to use
strings containing non-ASCII characters in a URL.
It's safe to use this filter on a string that has already gone through the
:tfilter:`urlencode` filter.
For example::
{{ value|iriencode }}
If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&me=2"``.
.. templatefilter:: join
``join``
--------
Joins a list with a string, like Python's ``str.join(list)``
For example::
{{ value|join:" // " }}
If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
``"a // b // c"``.
.. templatefilter:: json_script
``json_script``
---------------
.. versionadded:: 2.1
Safely outputs a Python object as JSON, wrapped in a ``<script>`` tag, ready
for use with JavaScript.
**Argument:** HTML "id" of the ``<script>`` tag.
For example::
{{ value|json_script:"hello-data" }}
If ``value`` is the dictionary ``{'hello': 'world'}``, the output will be:
.. code-block:: html
<script id="hello-data" type="application/json">{"hello": "world"}</script>
The resulting data can be accessed in JavaScript like this:
.. code-block:: javascript
var value = JSON.parse(document.getElementById('hello-data').textContent);
XSS attacks are mitigated by escaping the characters "<", ">" and "&". For
example if ``value`` is ``{'hello': 'world</script>&'}``, the output is:
.. code-block:: html
<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script>
This is compatible with a strict Content Security Policy that prohibits in-page
script execution. It also maintains a clean separation between passive data and
executable code.
.. templatefilter:: last
``last``
--------
Returns the last item in a list.
For example::
{{ value|last }}
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the
string ``"d"``.
.. templatefilter:: length
``length``
----------
Returns the length of the value. This works for both strings and lists.
For example::
{{ value|length }}
If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be
``4``.
The filter returns ``0`` for an undefined variable.
.. templatefilter:: length_is
``length_is``
-------------
Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
For example::
{{ value|length_is:"4" }}
If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be
``True``.
.. templatefilter:: linebreaks
``linebreaks``
--------------
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br>``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
For example::
{{ value|linebreaks }}
If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br>is a
slug</p>``.
.. templatefilter:: linebreaksbr
``linebreaksbr``
----------------
Converts all newlines in a piece of plain text to HTML line breaks
(``<br>``).
For example::
{{ value|linebreaksbr }}
If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br>is a
slug``.
.. templatefilter:: linenumbers
``linenumbers``
---------------
Displays text with line numbers.
For example::
{{ value|linenumbers }}
If ``value`` is::
one
two
three
the output will be::
1. one
2. two
3. three
.. templatefilter:: ljust
``ljust``
---------
Left-aligns the value in a field of a given width.
**Argument:** field size
For example::
"{{ value|ljust:"10" }}"
If ``value`` is ``Django``, the output will be ``"Django "``.
.. templatefilter:: lower
``lower``
---------
Converts a string into all lowercase.
For example::
{{ value|lower }}
If ``value`` is ``Totally LOVING this Album!``, the output will be
``totally loving this album!``.
.. templatefilter:: make_list
``make_list``
-------------
Returns the value turned into a list. For a string, it's a list of characters.
For an integer, the argument is cast to a string before creating a list.
For example::
{{ value|make_list }}
If ``value`` is the string ``"Joel"``, the output would be the list
``['J', 'o', 'e', 'l']``. If ``value`` is ``123``, the output will be the
list ``['1', '2', '3']``.
.. templatefilter:: phone2numeric
``phone2numeric``
-----------------
Converts a phone number (possibly containing letters) to its numerical
equivalent.
The input doesn't have to be a valid phone number. This will happily convert
any string.
For example::
{{ value|phone2numeric }}
If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
.. templatefilter:: pluralize
``pluralize``
-------------
Returns a plural suffix if the value is not ``1``, ``'1'``, or an object of
length 1. By default, this suffix is ``'s'``.
Example::
You have {{ num_messages }} message{{ num_messages|pluralize }}.
If ``num_messages`` is ``1``, the output will be ``You have 1 message.``
If ``num_messages`` is ``2`` the output will be ``You have 2 messages.``
For words that require a suffix other than ``'s'``, you can provide an alternate
suffix as a parameter to the filter.
Example::
You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.
For words that don't pluralize by simple suffix, you can specify both a
singular and plural suffix, separated by a comma.
Example::
You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
.. note:: Use :ttag:`blocktrans` to pluralize translated strings.
.. templatefilter:: pprint
``pprint``
----------
A wrapper around :func:`pprint.pprint` -- for debugging, really.
.. templatefilter:: random
``random``
----------
Returns a random item from the given list.
For example::
{{ value|random }}
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.
.. templatefilter:: rjust
``rjust``
---------
Right-aligns the value in a field of a given width.
**Argument:** field size
For example::
"{{ value|rjust:"10" }}"
If ``value`` is ``Django``, the output will be ``" Django"``.
.. templatefilter:: safe
``safe``
--------
Marks a string as not requiring further HTML escaping prior to output. When
autoescaping is off, this filter has no effect.
.. note::
If you are chaining filters, a filter applied after ``safe`` can
make the contents unsafe again. For example, the following code
prints the variable as is, unescaped::
{{ var|safe|escape }}
.. templatefilter:: safeseq
``safeseq``
-----------
Applies the :tfilter:`safe` filter to each element of a sequence. Useful in
conjunction with other filters that operate on sequences, such as
:tfilter:`join`. For example::
{{ some_list|safeseq|join:", " }}
You couldn't use the :tfilter:`safe` filter directly in this case, as it would
first convert the variable into a string, rather than working with the
individual elements of the sequence.
.. templatefilter:: slice
``slice``
---------
Returns a slice of the list.
Uses the same syntax as Python's list slicing. See
https://www.diveinto.org/python3/native-datatypes.html#slicinglists
for an introduction.
Example::
{{ some_list|slice:":2" }}
If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``.
.. templatefilter:: slugify
``slugify``
-----------
Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't
alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips
leading and trailing whitespace.
For example::
{{ value|slugify }}
If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
.. templatefilter:: stringformat
``stringformat``
----------------
Formats the variable according to the argument, a string formatting specifier.
This specifier uses the :ref:`old-string-formatting` syntax, with the exception
that the leading "%" is dropped.
For example::
{{ value|stringformat:"E" }}
If ``value`` is ``10``, the output will be ``1.000000E+01``.
.. templatefilter:: striptags
``striptags``
-------------
Makes all possible efforts to strip all [X]HTML tags.
For example::
{{ value|striptags }}
If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
output will be ``"Joel is a slug"``.
.. admonition:: No safety guarantee
Note that ``striptags`` doesn't give any guarantee about its output being
HTML safe, particularly with non valid HTML input. So **NEVER** apply the
``safe`` filter to a ``striptags`` output. If you are looking for something
more robust, you can use the ``bleach`` Python library, notably its
`clean`_ method.
.. _clean: https://bleach.readthedocs.io/en/latest/clean.html
.. templatefilter:: time
``time``
--------
Formats a time according to the given format.
Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom
format, same as the :tfilter:`date` filter. Note that the predefined format
is locale-dependent.
For example::
{{ value|time:"H:i" }}
If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
the string ``"01:23"``.
Another example:
Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
for example, ``"de"``, then for::
{{ value|time:"TIME_FORMAT" }}
the output will be the string ``"01:23"`` (The ``"TIME_FORMAT"`` format
specifier for the ``de`` locale as shipped with Django is ``"H:i"``).
The ``time`` filter will only accept parameters in the format string that
relate to the time of day, not the date (for obvious reasons). If you need to
format a ``date`` value, use the :tfilter:`date` filter instead (or along
``time`` if you need to render a full :py:class:`~datetime.datetime` value).
There is one exception the above rule: When passed a ``datetime`` value with
attached timezone information (a :ref:`time-zone-aware
<naive_vs_aware_datetimes>` ``datetime`` instance) the ``time`` filter will
accept the timezone-related :ref:`format specifiers
<date-and-time-formatting-specifiers>` ``'e'``, ``'O'`` , ``'T'`` and ``'Z'``.
When used without a format string, the ``TIME_FORMAT`` format specifier is
used::
{{ value|time }}
is the same as::
{{ value|time:"TIME_FORMAT" }}
.. templatefilter:: timesince
``timesince``
-------------
Formats a date as the time since that date (e.g., "4 days, 6 hours").
Takes an optional argument that is a variable containing the date to use as
the comparison point (without the argument, the comparison point is *now*).
For example, if ``blog_date`` is a date instance representing midnight on 1
June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
then the following would return "8 hours"::
{{ blog_date|timesince:comment_date }}
Comparing offset-naive and offset-aware datetimes will return an empty string.
Minutes is the smallest unit used, and "0 minutes" will be returned for any
date that is in the future relative to the comparison point.
.. templatefilter:: timeuntil
``timeuntil``
-------------
Similar to ``timesince``, except that it measures the time from now until the
given date or datetime. For example, if today is 1 June 2006 and
``conference_date`` is a date instance holding 29 June 2006, then
``{{ conference_date|timeuntil }}`` will return "4 weeks".
Takes an optional argument that is a variable containing the date to use as
the comparison point (instead of *now*). If ``from_date`` contains 22 June
2006, then the following will return "1 week"::
{{ conference_date|timeuntil:from_date }}
Comparing offset-naive and offset-aware datetimes will return an empty string.
Minutes is the smallest unit used, and "0 minutes" will be returned for any
date that is in the past relative to the comparison point.
.. templatefilter:: title
``title``
---------
Converts a string into titlecase by making words start with an uppercase
character and the remaining characters lowercase. This tag makes no effort to
keep "trivial words" in lowercase.
For example::
{{ value|title }}
If ``value`` is ``"my FIRST post"``, the output will be ``"My First Post"``.
.. templatefilter:: truncatechars
``truncatechars``
-----------------
Truncates a string if it is longer than the specified number of characters.
Truncated strings will end with a translatable ellipsis character ("…").
**Argument:** Number of characters to truncate to
For example::
{{ value|truncatechars:7 }}
If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel i…"``.
.. templatefilter:: truncatechars_html
``truncatechars_html``
----------------------
Similar to :tfilter:`truncatechars`, except that it is aware of HTML tags. Any
tags that are opened in the string and not closed before the truncation point
are closed immediately after the truncation.
For example::
{{ value|truncatechars_html:7 }}
If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be
``"<p>Joel i…</p>"``.
Newlines in the HTML content will be preserved.
.. templatefilter:: truncatewords
``truncatewords``
-----------------
Truncates a string after a certain number of words.
**Argument:** Number of words to truncate after
For example::
{{ value|truncatewords:2 }}
If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is …"``.
Newlines within the string will be removed.
.. templatefilter:: truncatewords_html
``truncatewords_html``
----------------------
Similar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any
tags that are opened in the string and not closed before the truncation point,
are closed immediately after the truncation.
This is less efficient than :tfilter:`truncatewords`, so should only be used
when it is being passed HTML text.
For example::
{{ value|truncatewords_html:2 }}
If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be
``"<p>Joel is …</p>"``.
Newlines in the HTML content will be preserved.
.. templatefilter:: unordered_list
``unordered_list``
------------------
Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var``
contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
``{{ var|unordered_list }}`` would return::
<li>States
<ul>
<li>Kansas
<ul>
<li>Lawrence</li>
<li>Topeka</li>
</ul>
</li>
<li>Illinois</li>
</ul>
</li>
.. templatefilter:: upper
``upper``
---------
Converts a string into all uppercase.
For example::
{{ value|upper }}
If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
.. templatefilter:: urlencode
``urlencode``
-------------
Escapes a value for use in a URL.
For example::
{{ value|urlencode }}
If ``value`` is ``"https://www.example.org/foo?a=b&c=d"``, the output will be
``"https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``.
An optional argument containing the characters which should not be escaped can
be provided.
If not provided, the '/' character is assumed safe. An empty string can be
provided when *all* characters should be escaped. For example::
{{ value|urlencode:"" }}
If ``value`` is ``"https://www.example.org/"``, the output will be
``"https%3A%2F%2Fwww.example.org%2F"``.
.. templatefilter:: urlize
``urlize``
----------
Converts URLs and email addresses in text into clickable links.
This template tag works on links prefixed with ``http://``, ``https://``, or
``www.``. For example, ``https://goo.gl/aia1t`` will get converted but
``goo.gl/aia1t`` won't.
It also supports domain-only links ending in one of the original top level
domains (``.com``, ``.edu``, ``.gov``, ``.int``, ``.mil``, ``.net``, and
``.org``). For example, ``djangoproject.com`` gets converted.
Links can have trailing punctuation (periods, commas, close-parens) and leading
punctuation (opening parens), and ``urlize`` will still do the right thing.
Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added
to them.
For example::
{{ value|urlize }}
If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
``"Check out <a href="http://www.djangoproject.com"
rel="nofollow">www.djangoproject.com</a>"``.
In addition to web links, ``urlize`` also converts email addresses into
``mailto:`` links. If ``value`` is
``"Send questions to foo@example.com"``, the output will be
``"Send questions to <a href="mailto:foo@example.com">foo@example.com</a>"``.
The ``urlize`` filter also takes an optional parameter ``autoescape``. If
``autoescape`` is ``True``, the link text and URLs will be escaped using
Django's built-in :tfilter:`escape` filter. The default value for
``autoescape`` is ``True``.
.. note::
If ``urlize`` is applied to text that already contains HTML markup, or to
email addresses that contain single quotes (``'``), things won't work as
expected. Apply this filter only to plain text.
.. templatefilter:: urlizetrunc
``urlizetrunc``
---------------
Converts URLs and email addresses into clickable links just like urlize_, but
truncates URLs longer than the given character limit.
**Argument:** Number of characters that link text should be truncated to,
including the ellipsis that's added if truncation is necessary.
For example::
{{ value|urlizetrunc:15 }}
If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
``'Check out <a href="http://www.djangoproject.com"
rel="nofollow">www.djangoproj…</a>'``.
As with urlize_, this filter should only be applied to plain text.
.. templatefilter:: wordcount
``wordcount``
-------------
Returns the number of words.
For example::
{{ value|wordcount }}
If ``value`` is ``"Joel is a slug"``, the output will be ``4``.
.. templatefilter:: wordwrap
``wordwrap``
------------
Wraps words at specified line length.
**Argument:** number of characters at which to wrap the text
For example::
{{ value|wordwrap:5 }}
If ``value`` is ``Joel is a slug``, the output would be::
Joel
is a
slug
.. templatefilter:: yesno
``yesno``
---------
Maps values for ``True``, ``False``, and (optionally) ``None``, to the strings
"yes", "no", "maybe", or a custom mapping passed as a comma-separated list, and
returns one of those strings according to the value:
For example::
{{ value|yesno:"yeah,no,maybe" }}
========== ====================== ===========================================
Value Argument Outputs
========== ====================== ===========================================
``True`` ``yes``
``True`` ``"yeah,no,maybe"`` ``yeah``
``False`` ``"yeah,no,maybe"`` ``no``
``None`` ``"yeah,no,maybe"`` ``maybe``
``None`` ``"yeah,no"`` ``no`` (converts ``None`` to ``False``
if no mapping for ``None`` is given)
========== ====================== ===========================================
Internationalization tags and filters
=====================================
Django provides template tags and filters to control each aspect of
:doc:`internationalization </topics/i18n/index>` in templates. They allow for
granular control of translations, formatting, and time zone conversions.
``i18n``
--------
This library allows specifying translatable text in templates.
To enable it, set :setting:`USE_I18N` to ``True``, then load it with
``{% load i18n %}``.
See :ref:`specifying-translation-strings-in-template-code`.
``l10n``
--------
This library provides control over the localization of values in templates.
You only need to load the library using ``{% load l10n %}``, but you'll often
set :setting:`USE_L10N` to ``True`` so that localization is active by default.
See :ref:`topic-l10n-templates`.
``tz``
------
This library provides control over time zone conversions in templates.
Like ``l10n``, you only need to load the library using ``{% load tz %}``,
but you'll usually also set :setting:`USE_TZ` to ``True`` so that conversion
to local time happens by default.
See :ref:`time-zones-in-templates`.
Other tags and filters libraries
================================
Django comes with a couple of other template-tag libraries that you have to
enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your
template with the :ttag:`{% load %}<load>` tag.
``django.contrib.humanize``
---------------------------
A set of Django template filters useful for adding a "human touch" to data. See
:doc:`/ref/contrib/humanize`.
``static``
----------
.. templatetag:: static
``static``
~~~~~~~~~~
To link to static files that are saved in :setting:`STATIC_ROOT` Django ships
with a :ttag:`static` template tag. If the :mod:`django.contrib.staticfiles`
app is installed, the tag will serve files using ``url()`` method of the
storage specified by :setting:`STATICFILES_STORAGE`. For example::
{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!">
It is also able to consume standard context variables, e.g. assuming a
``user_stylesheet`` variable is passed to the template::
{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen">
If you'd like to retrieve a static URL without displaying it, you can use a
slightly different call::
{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}">
.. admonition:: Using Jinja2 templates?
See :class:`~django.template.backends.jinja2.Jinja2` for information on
using the ``static`` tag with Jinja2.
.. templatetag:: get_static_prefix
``get_static_prefix``
~~~~~~~~~~~~~~~~~~~~~
You should prefer the :ttag:`static` template tag, but if you need more control
over exactly where and how :setting:`STATIC_URL` is injected into the template,
you can use the :ttag:`get_static_prefix` template tag::
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!">
There's also a second form you can use to avoid extra processing if you need
the value multiple times::
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!">
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!">
.. templatetag:: get_media_prefix
``get_media_prefix``
~~~~~~~~~~~~~~~~~~~~
Similar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a
template variable with the media prefix :setting:`MEDIA_URL`, e.g.::
{% load static %}
<body data-media-url="{% get_media_prefix %}">
By storing the value in a data attribute, we ensure it's escaped appropriately
if we want to use it in a JavaScript context.
|