Skip to content
Myr

nativetypes.py

This file

Path

src/jinja2/nativetypes.py

94 lines · 2.7 KiB · Python

Last changed by

native only evals at end of renderDavid Lordbefore adoptionf75cb42

History of this file

Take it

1from ast import literal_eval2from itertools import chain3from itertools import islice45from . import nodes6from ._compat import text_type7from .compiler import CodeGenerator8from .compiler import has_safe_repr9from .environment import Environment10from .environment import Template111213def native_concat(nodes):14    """Return a native Python type from the list of compiled nodes. If15    the result is a single node, its value is returned. Otherwise, the16    nodes are concatenated as strings. If the result can be parsed with17    :func:`ast.literal_eval`, the parsed value is returned. Otherwise,18    the string is returned.1920    :param nodes: Iterable of nodes to concatenate.21    """22    head = list(islice(nodes, 2))2324    if not head:25        return None2627    if len(head) == 1:28        raw = head[0]29    else:30        raw = u"".join([text_type(v) for v in chain(head, nodes)])3132    try:33        return literal_eval(raw)34    except (ValueError, SyntaxError, MemoryError):35        return raw363738class NativeCodeGenerator(CodeGenerator):39    """A code generator which renders Python types by not adding40    ``to_string()`` around output nodes.41    """4243    @staticmethod44    def _default_finalize(value):45        return value4647    def _output_const_repr(self, group):48        return repr(u"".join([text_type(v) for v in group]))4950    def _output_child_to_const(self, node, frame, finalize):51        const = node.as_const(frame.eval_ctx)5253        if not has_safe_repr(const):54            raise nodes.Impossible()5556        if isinstance(node, nodes.TemplateData):57            return const5859        return finalize.const(const)6061    def _output_child_pre(self, node, frame, finalize):62        if finalize.src is not None:63            self.write(finalize.src)6465    def _output_child_post(self, node, frame, finalize):66        if finalize.src is not None:67            self.write(")")686970class NativeEnvironment(Environment):71    """An environment that renders templates to native Python types."""7273    code_generator_class = NativeCodeGenerator747576class NativeTemplate(Template):77    environment_class = NativeEnvironment7879    def render(self, *args, **kwargs):80        """Render the template to produce a native Python type. If the81        result is a single node, its value is returned. Otherwise, the82        nodes are concatenated as strings. If the result can be parsed83        with :func:`ast.literal_eval`, the parsed value is returned.84        Otherwise, the string is returned.85        """86        vars = dict(*args, **kwargs)8788        try:89            return native_concat(self.root_render_func(self.new_context(vars)))90        except Exception:91            return self.environment.handle_exception()929394NativeEnvironment.template_class = NativeTemplate