Skip to content
Myr

Merge pull request #1083 from pallets/docs-changes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Address various documentation requests

authored by David Lord · committed by GitHub · parents 1949a5c, f9f1e3d · Browse files · 3 files+139 added−53 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+139 added−53 removed

  • other:+139 added−53 removed

3 files+139 added−53 removed

modified:docs/templates.rst+84 added-49 removed
55 unmodified lines
56* ``{# ... #}`` for :ref:`Comments` not included in the template output57* ``# ... ##`` for :ref:`Line Statements <line-statements>`585960Template File Extension61~~~~~~~~~~~~~~~~~~~~~~~6263As stated above, any file can be loaded as a template, regardless of64file extension. Adding a ``.jinja`` extension, like ``user.html.jinja``65may make it easier for some IDEs or editor plugins, but is not required.66Autoescaping, introduced later, can be applied based on file extension,67so you'll need to take the extra suffix into account in that case.6869Another good heuristic for identifying templates is that they are in a70``templates`` folder, regardless of extension. This is a common layout71for projects.727374.. _variables:7576Variables77---------
305 unmodified lines
383In this example, the ``{% block %}`` tags define four blocks that child templates384can fill in. All the `block` tag does is tell the template engine that a385child template may override those placeholders in the template.386387``block`` tags can be inside other blocks such as ``if``, but they will388always be executed regardless of if the ``if`` block is actually389rendered.390391Child Template392~~~~~~~~~~~~~~393394A child template might look like this::
189 unmodified lines
584When automatic escaping is enabled, everything is escaped by default except585for values explicitly marked as safe. Variables and expressions586can be marked as safe either in:587570a. the context dictionary by the application with `MarkupSafe.Markup`, or571b. the template, with the `|safe` filter588a. The context dictionary by the application with589 :class:`markupsafe.Markup`590b. The template, with the ``|safe`` filter.591573The main problem with this approach is that Python itself doesn't have the574concept of tainted values; so whether a value is safe or unsafe can get lost.592If a string that you marked safe is passed through other Python code593that doesn't understand that mark, it may get lost. Be aware of when594your data is marked safe and how it is processed before arriving at the595template.596576If a value is not marked safe, auto-escaping will take place; which means that577you could end up with double-escaped contents. Double-escaping is easy to578avoid, however: just rely on the tools Jinja2 provides and *don't use builtin579Python constructs such as str.format or the string modulo operator (%)*.597If a value has been escaped but is not marked safe, auto-escaping will598still take place and result in double-escaped characters. If you know599you have data that is already safe but not marked, be sure to wrap it in600``Markup`` or use the ``|safe`` filter.601602Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template603data that is marked as safe.604
586 unmodified lines
11911192The simplest form of expressions are literals. Literals are representations1193for Python objects such as strings and numbers. The following literals exist:11941174"Hello World":1195``"Hello World"``1196 Everything between two double or single quotes is a string. They are1197 useful whenever you need a string in the template (e.g. as1198 arguments to function calls and filters, or just to extend or include a1199 template).1200118042 / 123_456:1201``42`` / ``123_456``1202 Integers are whole numbers without a decimal part. The '_' character1203 can be used to separate groups for legibility.1204118442.23 / 42.1e2 / 123_456.789:1205``42.23`` / ``42.1e2`` / ``123_456.789``1206 Floating point numbers can be written using a '.' as a decimal mark.1207 They can also be written in scientific notation with an upper or1208 lower case 'e' to indicate the exponent part. The '_' character can1209 be used to separate groups for legibility, but cannot be used in the1210 exponent part.12111191['list', 'of', 'objects']:1212``['list', 'of', 'objects']``1213 Everything between two brackets is a list. Lists are useful for storing1214 sequential data to be iterated over. For example, you can easily1215 create a list of links using lists and tuples for (and with) a for loop::1216
3 unmodified lines
1220 <li><a href="{{ href }}">{{ caption }}</a></li>1221 {% endfor %}1222 </ul>12231203('tuple', 'of', 'values'):1224``('tuple', 'of', 'values')``1225 Tuples are like lists that cannot be modified ("immutable"). If a tuple1226 only has one item, it must be followed by a comma (``('1-tuple',)``).1227 Tuples are usually used to represent items of two or more elements.1228 See the list example above for more details.12291209{'dict': 'of', 'key': 'and', 'value': 'pairs'}:1230``{'dict': 'of', 'key': 'and', 'value': 'pairs'}``1231 A dict in Python is a structure that combines keys and values. Keys must1232 be unique and always have exactly one value. Dicts are rarely used in1233 templates; they are useful in some rare cases such as the :func:`xmlattr`1234 filter.12351215true / false:1216 true is always true and false is always false.1236``true`` / ``false``1237 ``true`` is always true and ``false`` is always false.12381239.. admonition:: Note12401241 The special constants `true`, `false`, and `none` are indeed lowercase.
9 unmodified lines
12511252Jinja allows you to calculate with values. This is rarely useful in templates1253but exists for completeness' sake. The following operators are supported:12541234\+1255``+``1256 Adds two objects together. Usually the objects are numbers, but if both are1257 strings or lists, you can concatenate them this way. This, however, is not1258 the preferred way to concatenate strings! For string concatenation, have1259 a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``.12601240\-1261``-``1262 Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.12631243/1264``/``1265 Divide two numbers. The return value will be a floating point number.1266 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.12671247//1268``//``1269 Divide two numbers and return the truncated integer result.1270 ``{{ 20 // 7 }}`` is ``2``.12711251%1272``%``1273 Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.12741254\*1275``*``1276 Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would1277 return ``4``. This can also be used to repeat a string multiple times.1278 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.12791259\**1280``**``1281 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``1282 would return ``8``.12831284Comparisons1285~~~~~~~~~~~12861266==1287``==``1288 Compares two objects for equality.12891269!=1290``!=``1291 Compares two objects for inequality.12921272>1273 `true` if the left hand side is greater than the right hand side.1293``>``1294 ``true`` if the left hand side is greater than the right hand side.12951275>=1276 `true` if the left hand side is greater or equal to the right hand side.1296``>=``1297 ``true`` if the left hand side is greater or equal to the right hand side.12981278<1279 `true` if the left hand side is lower than the right hand side.1299``<``1300 ``true`` if the left hand side is lower than the right hand side.13011281<=1282 `true` if the left hand side is lower or equal to the right hand side.1302``<=``1303 ``true`` if the left hand side is lower or equal to the right hand side.13041305Logic1306~~~~~13071287For `if` statements, `for` filtering, and `if` expressions, it can be useful to1308For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be useful to1309combine multiple expressions:13101290and1311``and``1312 Return true if the left and the right operand are true.13131293or1314``or``1315 Return true if the left or the right operand are true.13161296not1317``not``1318 negate a statement (see below).13191299(expr)1300 group an expression.1320``(expr)``1321 Parentheses group an expression.13221323.. admonition:: Note13241325 The ``is`` and ``in`` operators support negation using an infix notation,
7 unmodified lines
13331334The following operators are very useful but don't fit into any of the other1335two categories:13361316in1337``in``1338 Perform a sequence / mapping containment test. Returns true if the left1339 operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for1340 example, return true.13411321is1342``is``1343 Performs a :ref:`test <tests>`.13441324\|1345``|``1346 Applies a :ref:`filter <filters>`.13471327~1348``~``1349 Converts all operands into strings and concatenates them.13501351 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set1352 to ``'John'``) ``Hello John!``.13531333()1354``()``1355 Call a callable: ``{{ post.render() }}``. Inside of the parentheses you1356 can use positional arguments and keyword arguments like in Python:13571358 ``{{ post.render(user, full=true) }}``.13591339. / []1360``.`` / ``[]``1361 Get an attribute of an object. (See :ref:`variables`)136213631364.. _if-expression:
31 unmodified lines
1396.. code-block:: text13971398 {{ page.title.capitalize() }}13991379This also works for methods on user-defined types.1380For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1381you can do the following:1400This works for methods on user-defined types. For example, if variable1401``f`` of type ``Foo`` has a method ``bar`` defined on it, you can do the1402following:14031404.. code-block:: text14051385 {{ f.bar() }}1406 {{ f.bar(value) }}14071408Operator methods also work as expected. For example, ``%`` implements1409printf-style for strings:14101411.. code-block:: text14121413 {{ "Hello, %s!" % name }}14141415Although you should prefer the ``.format`` method for that case (which1416is a bit contrived in the context of rendering a template):14171418.. code-block:: text14191420 {{ "Hello, {}!".format(name) }}142114221423.. _builtin-filters:14241425List of Builtin Filters1426-----------------------
371 unmodified lines
modified:jinja2/filters.py+50 added-4 removed
741 unmodified lines
742 return default743744745def do_format(value, *args, **kwargs):746 """747 Apply python string formatting on an object:746 """Apply the given values to a `printf-style`_ format string, like747 ``string % values``.748749 .. sourcecode:: jinja750751 {{ "%s - %s"|format("Hello?", "Foo!") }}752 -> Hello? - Foo!751 {{ "%s, %s!"|format(greeting, name) }}752 Hello, World!753754 In most cases it should be more convenient and efficient to use the755 ``%`` operator or :meth:`str.format`.756757 .. code-block:: text758759 {{ "%s, %s!" % (greeting, name) }}760 {{ "{}, {}!".format(greeting, name) }}761762 .. _printf-style: https://docs.python.org/library/stdtypes.html763 #printf-style-string-formatting764 """765 if args and kwargs:766 raise FilterArgumentError('can\'t handle positional and keyword '767 'arguments at the same time')
273 unmodified lines
1041 .. sourcecode:: jinja10421043 Users on this page: {{ titles|map('lower')|join(', ') }}10441045 Similar to a generator comprehension such as:10461047 .. code-block:: python10481049 (u.username for u in users)1050 (u.username or "Anonymous" for u in users)1051 (do_lower(x) for x in titles)10521053 .. versionchanged:: 2.11.01054 Added the ``default`` parameter.10551056 .. versionadded:: 2.7
20 unmodified lines
1077 {{ numbers|select("divisibleby", 3) }}1078 {{ numbers|select("lessthan", 42) }}1079 {{ strings|select("equalto", "mystring") }}10801081 Similar to a generator comprehension such as:10821083 .. code-block:: python10841085 (n for n in numbers if test_odd(n))1086 (n for n in numbers if test_divisibleby(n, 3))10871088 .. versionadded:: 2.71089 """1090 return select_or_reject(args, kwargs, lambda x: x, False)1091
10 unmodified lines
1102 .. sourcecode:: jinja11031104 {{ numbers|reject("odd") }}11051106 Similar to a generator comprehension such as:11071108 .. code-block:: python11091110 (n for n in numbers if not test_odd(n))11111112 .. versionadded:: 2.71113 """1114 return select_or_reject(args, kwargs, lambda x: not x, False)1115
13 unmodified lines
11291130 {{ users|selectattr("is_active") }}1131 {{ users|selectattr("email", "none") }}11321133 Similar to a generator comprehension such as:11341135 .. code-block:: python11361137 (u for user in users if user.is_active)1138 (u for user in users if test_none(user.email))11391140 .. versionadded:: 2.71141 """1142 return select_or_reject(args, kwargs, lambda x: x, True)1143
11 unmodified lines
11551156 {{ users|rejectattr("is_active") }}1157 {{ users|rejectattr("email", "none") }}11581159 Similar to a generator comprehension such as:11601161 .. code-block:: python11621163 (u for user in users if not user.is_active)1164 (u for user in users if not test_none(user.email))11651166 .. versionadded:: 2.71167 """1168 return select_or_reject(args, kwargs, lambda x: not x, True)1169
148 unmodified lines
modified:jinja2/nodes.py+5 added
940 unmodified lines
941 variable named `foo`::942943 Assign(Name('foo', ctx='store'),944 Getattr(ContextReference(), 'name'))945946 This is basically equivalent to using the947 :func:`~jinja2.contextfunction` decorator when using the948 high-level API, which causes a reference to the context to be passed949 as the first argument to a function.950 """951952953class Continue(Stmt):
51 unmodified lines