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
Provenance
- Commit
91893a4- Tree
686e5ee- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1949a5c- Parent 2
f9f1e3d
3 files changed+139 added−53 removed
modified:docs/templates.rst+84 added-49 removed
55 unmodified lines56 * ``{# ... #}`` for :ref:`Comments` not included in the template output57 * ``# ... ##`` for :ref:`Line Statements <line-statements>`58 59 60+Template File Extension61+~~~~~~~~~~~~~~~~~~~~~~~62+63+As stated above, any file can be loaded as a template, regardless of64+file extension. Adding a ``.jinja`` extension, like ``user.html.jinja``65+may make it easier for some IDEs or editor plugins, but is not required.66+Autoescaping, introduced later, can be applied based on file extension,67+so you'll need to take the extra suffix into account in that case.68+69+Another good heuristic for identifying templates is that they are in a70+``templates`` folder, regardless of extension. This is a common layout71+for projects.72+73+74 .. _variables:75 76 Variables77 ---------305 unmodified lines383 In this example, the ``{% block %}`` tags define four blocks that child templates384 can fill in. All the `block` tag does is tell the template engine that a385 child template may override those placeholders in the template.386 387+``block`` tags can be inside other blocks such as ``if``, but they will388+always be executed regardless of if the ``if`` block is actually389+rendered.390+391 Child Template392 ~~~~~~~~~~~~~~393 394 A child template might look like this::189 unmodified lines584 When automatic escaping is enabled, everything is escaped by default except585 for values explicitly marked as safe. Variables and expressions586 can be marked as safe either in:587 570-a. the context dictionary by the application with `MarkupSafe.Markup`, or571-b. the template, with the `|safe` filter588+a. The context dictionary by the application with589+ :class:`markupsafe.Markup`590+b. The template, with the ``|safe`` filter.591 573-The main problem with this approach is that Python itself doesn't have the574-concept of tainted values; so whether a value is safe or unsafe can get lost.592+If a string that you marked safe is passed through other Python code593+that doesn't understand that mark, it may get lost. Be aware of when594+your data is marked safe and how it is processed before arriving at the595+template.596 576-If a value is not marked safe, auto-escaping will take place; which means that577-you could end up with double-escaped contents. Double-escaping is easy to578-avoid, however: just rely on the tools Jinja2 provides and *don't use builtin579-Python constructs such as str.format or the string modulo operator (%)*.597+If a value has been escaped but is not marked safe, auto-escaping will598+still take place and result in double-escaped characters. If you know599+you have data that is already safe but not marked, be sure to wrap it in600+``Markup`` or use the ``|safe`` filter.601 602 Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template603 data that is marked as safe.604 586 unmodified lines1191 1192 The simplest form of expressions are literals. Literals are representations1193 for Python objects such as strings and numbers. The following literals exist:1194 1174-"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).1200 1180-42 / 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.1204 1184-42.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.1211 1191-['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 lines1220 <li><a href="{{ href }}">{{ caption }}</a></li>1221 {% endfor %}1222 </ul>1223 1203-('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.1229 1209-{'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.1235 1215-true / false:1216- true is always true and false is always false.1236+``true`` / ``false``1237+ ``true`` is always true and ``false`` is always false.1238 1239 .. admonition:: Note1240 1241 The special constants `true`, `false`, and `none` are indeed lowercase.9 unmodified lines1251 1252 Jinja allows you to calculate with values. This is rarely useful in templates1253 but exists for completeness' sake. The following operators are supported:1254 1234-\+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``.1260 1240-\-1261+``-``1262 Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.1263 1243-/1264+``/``1265 Divide two numbers. The return value will be a floating point number.1266 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.1267 1247-//1268+``//``1269 Divide two numbers and return the truncated integer result.1270 ``{{ 20 // 7 }}`` is ``2``.1271 1251-%1272+``%``1273 Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.1274 1254-\*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.1279 1259-\**1280+``**``1281 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``1282 would return ``8``.1283 1284 Comparisons1285 ~~~~~~~~~~~1286 1266-==1287+``==``1288 Compares two objects for equality.1289 1269-!=1290+``!=``1291 Compares two objects for inequality.1292 1272->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.1295 1275->=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.1298 1278-<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.1301 1281-<=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.1304 1305 Logic1306 ~~~~~1307 1287-For `if` statements, `for` filtering, and `if` expressions, it can be useful to1308+For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be useful to1309 combine multiple expressions:1310 1290-and1311+``and``1312 Return true if the left and the right operand are true.1313 1293-or1314+``or``1315 Return true if the left or the right operand are true.1316 1296-not1317+``not``1318 negate a statement (see below).1319 1299-(expr)1300- group an expression.1320+``(expr)``1321+ Parentheses group an expression.1322 1323 .. admonition:: Note1324 1325 The ``is`` and ``in`` operators support negation using an infix notation,7 unmodified lines1333 1334 The following operators are very useful but don't fit into any of the other1335 two categories:1336 1316-in1337+``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.1341 1321-is1342+``is``1343 Performs a :ref:`test <tests>`.1344 1324-\|1345+``|``1346 Applies a :ref:`filter <filters>`.1347 1327-~1348+``~``1349 Converts all operands into strings and concatenates them.1350 1351 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set1352 to ``'John'``) ``Hello John!``.1353 1333-()1354+``()``1355 Call a callable: ``{{ post.render() }}``. Inside of the parentheses you1356 can use positional arguments and keyword arguments like in Python:1357 1358 ``{{ post.render(user, full=true) }}``.1359 1339-. / []1360+``.`` / ``[]``1361 Get an attribute of an object. (See :ref:`variables`)1362 1363 1364 .. _if-expression:31 unmodified lines1396 .. code-block:: text1397 1398 {{ page.title.capitalize() }}1399 1379-This also works for methods on user-defined types.1380-For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1381-you can do the following:1400+This 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 the1402+following:1403 1404 .. code-block:: text1405 1385- {{ f.bar() }}1406+ {{ f.bar(value) }}1407 1408+Operator methods also work as expected. For example, ``%`` implements1409+printf-style for strings:1410 1411+.. code-block:: text1412+1413+ {{ "Hello, %s!" % name }}1414+1415+Although you should prefer the ``.format`` method for that case (which1416+is a bit contrived in the context of rendering a template):1417+1418+.. code-block:: text1419+1420+ {{ "Hello, {}!".format(name) }}1421+1422+1423 .. _builtin-filters:1424 1425 List of Builtin Filters1426 -----------------------371 unmodified linesmodified:jinja2/filters.py+50 added-4 removed
741 unmodified lines742 return default743 744 745 def 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``.748 749 .. sourcecode:: jinja750 751- {{ "%s - %s"|format("Hello?", "Foo!") }}752- -> Hello? - Foo!751+ {{ "%s, %s!"|format(greeting, name) }}752+ Hello, World!753+754+ In most cases it should be more convenient and efficient to use the755+ ``%`` operator or :meth:`str.format`.756+757+ .. code-block:: text758+759+ {{ "%s, %s!" % (greeting, name) }}760+ {{ "{}, {}!".format(greeting, name) }}761+762+ .. _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 lines1041 .. sourcecode:: jinja1042 1043 Users on this page: {{ titles|map('lower')|join(', ') }}1044 1045+ Similar to a generator comprehension such as:1046+1047+ .. code-block:: python1048+1049+ (u.username for u in users)1050+ (u.username or "Anonymous" for u in users)1051+ (do_lower(x) for x in titles)1052+1053 .. versionchanged:: 2.11.01054 Added the ``default`` parameter.1055 1056 .. versionadded:: 2.720 unmodified lines1077 {{ numbers|select("divisibleby", 3) }}1078 {{ numbers|select("lessthan", 42) }}1079 {{ strings|select("equalto", "mystring") }}1080 1081+ Similar to a generator comprehension such as:1082+1083+ .. code-block:: python1084+1085+ (n for n in numbers if test_odd(n))1086+ (n for n in numbers if test_divisibleby(n, 3))1087+1088 .. versionadded:: 2.71089 """1090 return select_or_reject(args, kwargs, lambda x: x, False)1091 10 unmodified lines1102 .. sourcecode:: jinja1103 1104 {{ numbers|reject("odd") }}1105 1106+ Similar to a generator comprehension such as:1107+1108+ .. code-block:: python1109+1110+ (n for n in numbers if not test_odd(n))1111+1112 .. versionadded:: 2.71113 """1114 return select_or_reject(args, kwargs, lambda x: not x, False)1115 13 unmodified lines1129 1130 {{ users|selectattr("is_active") }}1131 {{ users|selectattr("email", "none") }}1132 1133+ Similar to a generator comprehension such as:1134+1135+ .. code-block:: python1136+1137+ (u for user in users if user.is_active)1138+ (u for user in users if test_none(user.email))1139+1140 .. versionadded:: 2.71141 """1142 return select_or_reject(args, kwargs, lambda x: x, True)1143 11 unmodified lines1155 1156 {{ users|rejectattr("is_active") }}1157 {{ users|rejectattr("email", "none") }}1158 1159+ Similar to a generator comprehension such as:1160+1161+ .. code-block:: python1162+1163+ (u for user in users if not user.is_active)1164+ (u for user in users if not test_none(user.email))1165+1166 .. versionadded:: 2.71167 """1168 return select_or_reject(args, kwargs, lambda x: not x, True)1169 148 unmodified linesmodified:jinja2/nodes.py+5 added
940 unmodified lines941 variable named `foo`::942 943 Assign(Name('foo', ctx='store'),944 Getattr(ContextReference(), 'name'))945+946+ 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 """951 952 953 class Continue(Stmt):51 unmodified lines