Skip to content
Myr

preserve quotes between nodes in native env

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 · parent afd6c48 · Browse files · 3 files+52 added−18 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+52 added−18 removed

  • tests:+17 added−1 removed
  • other:+35 added−17 removed

3 files+52 added−18 removed

modified:jinja2/nativetypes.py+32 added-17 removed
7 unmodified lines
8from jinja2.environment import Environment, Template9from jinja2.utils import concat, escape101112def native_concat(nodes):13 """Return a native Python type from the list of compiled nodes. If the14 result is a single node, its value is returned. Otherwise, the nodes are15 concatenated as strings. If the result can be parsed with16 :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the17 string is returned.12def native_concat(nodes, preserve_quotes=True):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.20 :param preserve_quotes: Whether to re-wrap literal strings with21 quotes, to preserve quotes around expressions for later parsing.22 Should be ``False`` in :meth:`NativeEnvironment.render`.23 """24 head = list(islice(nodes, 2))2526 if not head:27 return None2829 if len(head) == 1:25 out = head[0]30 raw = head[0]31 else:32 if isinstance(nodes, types.GeneratorType):33 nodes = chain(head, nodes)29 out = u''.join([text_type(v) for v in nodes])34 raw = u''.join([text_type(v) for v in nodes])3536 try:32 return literal_eval(out)37 literal = literal_eval(raw)38 except (ValueError, SyntaxError, MemoryError):34 return out39 return raw4041 # If literal_eval returned a string, re-wrap with the original42 # quote character to avoid dropping quotes between expression nodes.43 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should44 # be ('a', 'b').45 if preserve_quotes and isinstance(literal, str):46 return "{quote}{}{quote}".format(literal, quote=raw[0])4748 return literal495051class NativeCodeGenerator(CodeGenerator):52 """A code generator which avoids injecting ``to_string()`` calls around the53 internal code Jinja uses to render templates.54 """
158 unmodified lines
213214215class NativeTemplate(Template):216 def render(self, *args, **kwargs):203 """Render the template to produce a native Python type. If the result204 is a single node, its value is returned. Otherwise, the nodes are205 concatenated as strings. If the result can be parsed with206 :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the207 string is returned.217 """Render the template to produce a native Python type. If the218 result is a single node, its value is returned. Otherwise, the219 nodes are concatenated as strings. If the result can be parsed220 with :func:`ast.literal_eval`, the parsed value is returned.221 Otherwise, the string is returned.222 """223 vars = dict(*args, **kwargs)210224 try:212 return native_concat(self.root_render_func(self.new_context(vars)))225 return native_concat(226 self.root_render_func(self.new_context(vars)), preserve_quotes=False227 )228 except Exception:229 exc_info = sys.exc_info()230231 return self.environment.handle_exception(exc_info, True)
7 unmodified lines
modified:tests/test_nativetypes.py+17 added-1 removed
107 unmodified lines
108 result = t.render()109 assert not isinstance(result, type)110 assert result in ["<type 'bool'>", "<class 'bool'>"]111112 def test_string(self, env):112 def test_string_literal_var(self, env):113 t = env.from_string("[{{ 'all' }}]")114 result = t.render()115 assert isinstance(result, text_type)116 assert result == "[all]"117118 def test_string_top_level(self, env):119 t = env.from_string("'Jinja'")120 result = t.render()121 assert result == 'Jinja'122123 def test_tuple_of_variable_strings(self, env):124 t = env.from_string("'{{ a }}', 'data', '{{ b }}', b'{{ c }}'")125 result = t.render(a=1, b=2, c="bytes")126 assert isinstance(result, tuple)127 assert result == ("1", "data", "2", b"bytes")128129 def test_concat_strings_with_quotes(self, env):130 t = env.from_string("--host='{{ host }}' --user \"{{ user }}\"")131 result = t.render(host="localhost", user="Jinja")132 assert result == "--host='localhost' --user \"Jinja\""
modified:CHANGES.rst+3 added
50 unmodified lines
51 :issue:`970`52- Support :class:`os.PathLike` objects in53 :class:`~loader.FileSystemLoader` and :class:`~loader.ModuleLoader`.54 :issue:`870`55- :class:`~nativetypes.NativeTemplate` correctly handles quotes56 between expressions. ``"'{{ a }}', '{{ b }}'"`` renders as the tuple57 ``('1', '2')`` rather than the string ``'1, 2'``. :issue:`1020`585960Version 2.10.361--------------
629 unmodified lines