Skip to content
Myr

Merge branch '2.11.x'

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

authored by David Lord · committed by David Lord · parents 91eb39b, 9ec465b · Browse files · 5 files+127 added−33 removed
This commit

State

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

Diff stats

5 files+127 added−33 removed

  • tests:+103 added−0 removed
  • other:+24 added−33 removed

5 files+127 added−33 removed

modified:src/jinja2/lexer.py+8 added-5 removed
635 unmodified lines
636 source_length = len(source)637 balancing_stack = []638 lstrip_unless_re = self.lstrip_unless_re639 newlines_stripped = 0640 line_starting = True641642 while 1:643 # tokenizer loop644 for regex, tokens, new_state in statetokens:
41 unmodified lines
686 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)687 ):688 # The start of text between the last newline and the tag.689 l_pos = text.rfind("\n") + 1690 if l_pos > 0 or line_starting:691 # If there's only whitespace between the newline and the692 # tag, strip it.693 if not lstrip_unless_re.search(text, l_pos):694 groups = (text[:l_pos],) + groups[1:]695690 # If there's only whitespace between the newline and the691 # tag, strip it.692 if not lstrip_unless_re.search(text, l_pos):693 groups = (text[:l_pos],) + groups[1:]694696 for idx, token in enumerate(tokens):697 # failure group698 if token.__class__ is Failure:699 raise token(lineno, filename)
47 unmodified lines
747 if data or tokens not in ignore_if_empty:748 yield lineno, tokens, data749 lineno += data.count("\n")750751 line_starting = m.group()[-1:] == "\n"752753 # fetch new position into new variable so that we can check754 # if there is a internal parsing error which would result755 # in an infinite loop756 pos2 = m.end()
41 unmodified lines
modified:src/jinja2/nativetypes.py+7 added-25 removed
1import types1from ast import literal_eval2from itertools import chain3from itertools import islice4
3 unmodified lines
8from .environment import Environment9from .environment import Template101113def native_concat(nodes, preserve_quotes=True):12def native_concat(nodes):13 """Return a native Python type from the list of compiled nodes. If14 the result is a single node, its value is returned. Otherwise, the15 nodes are concatenated as strings. If the result can be parsed with16 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,17 the string is returned.1819 :param nodes: Iterable of nodes to concatenate.21 :param preserve_quotes: Whether to re-wrap literal strings with22 quotes, to preserve quotes around expressions for later parsing.23 Should be ``False`` in :meth:`NativeEnvironment.render`.20 """21 head = list(islice(nodes, 2))2223 if not head:
1 unmodified line
2526 if len(head) == 1:27 raw = head[0]28 else:33 if isinstance(nodes, types.GeneratorType):34 nodes = chain(head, nodes)35 raw = "".join([str(v) for v in nodes])29 raw = "".join([str(v) for v in chain(head, nodes)])3031 try:38 literal = literal_eval(raw)32 return literal_eval(raw)33 except (ValueError, SyntaxError, MemoryError):34 return raw3542 # If literal_eval returned a string, re-wrap with the original43 # quote character to avoid dropping quotes between expression nodes.44 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should45 # be ('a', 'b').46 if preserve_quotes and isinstance(literal, str):47 quote = raw[0]48 return f"{quote}{literal}{quote}"3650 return literal515237class NativeCodeGenerator(CodeGenerator):38 """A code generator which renders Python types by not adding55 ``str()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.39 ``str()`` around output nodes.40 """4142 @staticmethod43 def _default_finalize(value):44 return value4546 def _output_const_repr(self, group):64 return repr(native_concat(group))47 return repr("".join([str(v) for v in group]))4849 def _output_child_to_const(self, node, frame, finalize):50 const = node.as_const(frame.eval_ctx)51
30 unmodified lines
82 with :func:`ast.literal_eval`, the parsed value is returned.83 Otherwise, the string is returned.84 """85 vars = dict(*args, **kwargs)8687 try:104 return native_concat(105 self.root_render_func(self.new_context(vars)), preserve_quotes=False106 )88 return native_concat(self.root_render_func(self.new_context(vars)))89 except Exception:90 return self.environment.handle_exception()9192
1 unmodified line
modified:tests/test_lexnparse.py+92 added
711 unmodified lines
712 <%endfor%>"""713 )714 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))715716 def test_lstrip_blocks_outside_with_new_line(self):717 env = Environment(lstrip_blocks=True, trim_blocks=False)718 tmpl = env.from_string(719 " {% if kvs %}(\n"720 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"721 " ){% endif %}"722 )723 out = tmpl.render(kvs=[("a", 1), ("b", 2)])724 assert out == "(\na=1 b=2 \n )"725726 def test_lstrip_trim_blocks_outside_with_new_line(self):727 env = Environment(lstrip_blocks=True, trim_blocks=True)728 tmpl = env.from_string(729 " {% if kvs %}(\n"730 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"731 " ){% endif %}"732 )733 out = tmpl.render(kvs=[("a", 1), ("b", 2)])734 assert out == "(\na=1 b=2 )"735736 def test_lstrip_blocks_inside_with_new_line(self):737 env = Environment(lstrip_blocks=True, trim_blocks=False)738 tmpl = env.from_string(739 " ({% if kvs %}\n"740 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"741 " {% endif %})"742 )743 out = tmpl.render(kvs=[("a", 1), ("b", 2)])744 assert out == " (\na=1 b=2 \n)"745746 def test_lstrip_trim_blocks_inside_with_new_line(self):747 env = Environment(lstrip_blocks=True, trim_blocks=True)748 tmpl = env.from_string(749 " ({% if kvs %}\n"750 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"751 " {% endif %})"752 )753 out = tmpl.render(kvs=[("a", 1), ("b", 2)])754 assert out == " (a=1 b=2 )"755756 def test_lstrip_blocks_without_new_line(self):757 env = Environment(lstrip_blocks=True, trim_blocks=False)758 tmpl = env.from_string(759 " {% if kvs %}"760 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"761 " {% endif %}"762 )763 out = tmpl.render(kvs=[("a", 1), ("b", 2)])764 assert out == " a=1 b=2 "765766 def test_lstrip_trim_blocks_without_new_line(self):767 env = Environment(lstrip_blocks=True, trim_blocks=True)768 tmpl = env.from_string(769 " {% if kvs %}"770 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"771 " {% endif %}"772 )773 out = tmpl.render(kvs=[("a", 1), ("b", 2)])774 assert out == " a=1 b=2 "775776 def test_lstrip_blocks_consume_after_without_new_line(self):777 env = Environment(lstrip_blocks=True, trim_blocks=False)778 tmpl = env.from_string(779 " {% if kvs -%}"780 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"781 " {% endif -%}"782 )783 out = tmpl.render(kvs=[("a", 1), ("b", 2)])784 assert out == "a=1 b=2 "785786 def test_lstrip_trim_blocks_consume_before_without_new_line(self):787 env = Environment(lstrip_blocks=False, trim_blocks=False)788 tmpl = env.from_string(789 " {%- if kvs %}"790 " {%- for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"791 " {%- endif %}"792 )793 out = tmpl.render(kvs=[("a", 1), ("b", 2)])794 assert out == "a=1 b=2 "795796 def test_lstrip_trim_blocks_comment(self):797 env = Environment(lstrip_blocks=True, trim_blocks=True)798 tmpl = env.from_string(" {# 1 space #}\n {# 2 spaces #} {# 4 spaces #}")799 out = tmpl.render()800 assert out == " " * 4801802 def test_lstrip_trim_blocks_raw(self):803 env = Environment(lstrip_blocks=True, trim_blocks=True)804 tmpl = env.from_string("{{x}}\n{%- raw %} {% endraw -%}\n{{ y }}")805 out = tmpl.render(x=1, y=2)806 assert out == "1 2"807808 def test_php_syntax_with_manual(self, env):809 env = Environment(810 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True811 )
94 unmodified lines
modified:tests/test_nativetypes.py+11 added
1import math23import pytest45from jinja2.exceptions import UndefinedError6from jinja2.nativetypes import NativeEnvironment
127 unmodified lines
134 result = t.render(host="localhost", user="Jinja")135 assert result == "--host='localhost' --user \"Jinja\""136137138def test_no_intermediate_eval(env):139 t = env.from_string("0.000{{ a }}")140 result = t.render(a=7)141 assert isinstance(result, float)142 # If intermediate eval happened, 0.000 would render 0.0, then 7143 # would be appended, resulting in 0.07.144 assert math.isclose(result, 0.0007)145146147def test_spontaneous_env():148 t = NativeTemplate("{{ true }}")149 assert isinstance(t.environment, NativeEnvironment)
modified:CHANGES.rst+9 added-3 removed
11 unmodified lines
12- Use :pep:`451` API to load templates with13 :class:`~loaders.PackageLoader`. :issue:`1168`1415162.11.217------16Version 2.11.217--------------1819Unreleased19Released 2020-04-132021- Fix a bug that caused callable objects with ``__getattr__``, like22 :class:`~unittest.mock.Mock` to be treated as a23 :func:`contextfunction`. :issue:`1145`
13 unmodified lines
37- Fix line numbers in error messages when newlines are stripped.38 :pr:`1178`39- The special ``namespace()`` assignment object in templates works in40 async environments. :issue:`1180`41- Fix whitespace being removed before tags in the middle of lines when42 ``lstrip_blocks`` is enabled. :issue:`1138`43- :class:`~nativetypes.NativeEnvironment` doesn't evaluate44 intermediate strings during rendering. This prevents early45 evaluation which could change the value of an expression.46 :issue:`1186`474849Version 2.11.150--------------
737 unmodified lines