Пример #1
0
    def _fail_ut_eof(self, name, end_token_stack, lineno):
        expected = []
        for exprs in end_token_stack:
            expected.extend(imap(describe_token_expr, exprs))
        if end_token_stack:
            currently_looking = ' or '.join(
                "'{0!s}'".format(describe_token_expr(expr))
                for expr in end_token_stack[-1])
        else:
            currently_looking = None

        if name is None:
            message = ['Unexpected end of template.']
        else:
            message = ['Encountered unknown tag \'{0!s}\'.'.format(name)]

        if currently_looking:
            if name is not None and name in expected:
                message.append('You probably made a nesting mistake. Jinja '
                               'is expecting this tag, but currently looking '
                               'for %s.' % currently_looking)
            else:
                message.append('Jinja was looking for the following tags: '
                               '%s.' % currently_looking)

        if self._tag_stack:
            message.append('The innermost block that needs to be '
                           'closed is \'%s\'.' % self._tag_stack[-1])

        self.fail(' '.join(message), lineno)
Пример #2
0
    def _fail_ut_eof(self, name, end_token_stack, lineno):
        expected = []
        for exprs in end_token_stack:
            expected.extend(imap(describe_token_expr, exprs))
        if end_token_stack:
            currently_looking = ' or '.join("'%s'" % describe_token_expr(expr)
                                            for expr in end_token_stack[-1])
        else:
            currently_looking = None

        if name is None:
            message = ['Unexpected end of template.']
        else:
            message = ['Encountered unknown tag \'%s\'.' % name]

        if currently_looking:
            if name is not None and name in expected:
                message.append('You probably made a nesting mistake. Jinja '
                               'is expecting this tag, but currently looking '
                               'for %s.' % currently_looking)
            else:
                message.append('Jinja was looking for the following tags: '
                               '%s.' % currently_looking)

        if self._tag_stack:
            message.append('The innermost block that needs to be '
                           'closed is \'%s\'.' % self._tag_stack[-1])

        self.fail(' '.join(message), lineno)
Пример #3
0
    def _fail_ut_eof(self, name, end_token_stack, lineno):
        expected = []
        for exprs in end_token_stack:
            expected.extend(imap(describe_token_expr, exprs))
        if end_token_stack:
            currently_looking = " or ".join("'%s'" % describe_token_expr(expr)
                                            for expr in end_token_stack[-1])
        else:
            currently_looking = None

        if name is None:
            message = ["Unexpected end of template."]
        else:
            message = ["Encountered unknown tag '%s'." % name]

        if currently_looking:
            if name is not None and name in expected:
                message.append("You probably made a nesting mistake. Jinja "
                               "is expecting this tag, but currently looking "
                               "for %s." % currently_looking)
            else:
                message.append("Jinja was looking for the following tags: "
                               "%s." % currently_looking)

        if self._tag_stack:
            message.append("The innermost block that needs to be "
                           "closed is '%s'." % self._tag_stack[-1])

        self.fail(" ".join(message), lineno)
Пример #4
0
def do_join(eval_ctx, value, d=u'', attribute=None):
    """Return a string which is the concatenation of the strings in the
    sequence. The separator between elements is an empty string per
    default, you can define it with the optional parameter:

    .. sourcecode:: jinja

        {{ [1, 2, 3]|join('|') }}
            -> 1|2|3

        {{ [1, 2, 3]|join }}
            -> 123

    It is also possible to join certain attributes of an object:

    .. sourcecode:: jinja

        {{ users|join(', ', attribute='username') }}

    .. versionadded:: 2.6
       The `attribute` parameter was added.
    """
    if attribute is not None:
        value = imap(make_attrgetter(eval_ctx.environment, attribute), value)

    # no automatic escaping?  joining is a lot eaiser then
    if not eval_ctx.autoescape:
        return text_type(d).join(imap(text_type, value))

    # if the delimiter doesn't have an html representation we check
    # if any of the items has.  If yes we do a coercion to Markup
    if not hasattr(d, '__html__'):
        value = list(value)
        do_escape = False
        for idx, item in enumerate(value):
            if hasattr(item, '__html__'):
                do_escape = True
            else:
                value[idx] = text_type(item)
        if do_escape:
            d = escape(d)
        else:
            d = text_type(d)
        return d.join(value)

    # no html involved, to normal joining
    return soft_unicode(d).join(imap(soft_unicode, value))
Пример #5
0
 def debug_info(self):
     """The debug info mapping."""
     if self._debug_info:
         return [
             tuple(imap(int, x.split('=')))
             for x in self._debug_info.split('&')
         ]
     return []
Пример #6
0
def markup_join(seq):
    """Concatenation that escapes if necessary and converts to unicode."""
    buf = []
    iterator = imap(soft_unicode, seq)
    for arg in iterator:
        buf.append(arg)
        if hasattr(arg, '__html__'):
            return Markup(u'').join(chain(buf, iterator))
    return concat(buf)
Пример #7
0
def markup_join(seq):
    """Concatenation that escapes if necessary and converts to unicode."""
    buf = []
    iterator = imap(soft_unicode, seq)
    for arg in iterator:
        buf.append(arg)
        if hasattr(arg, '__html__'):
            return Markup(u'').join(chain(buf, iterator))
    return concat(buf)
Пример #8
0
    def visit_FromImport(self, node, frame):
        """Visit named imports."""
        self.newline(node)
        self.write('included_template = environment.get_template(')
        self.visit(node.template, frame)
        self.write(', %r).' % self.name)
        if node.with_context:
            self.write('make_module(context.parent, True)')
        else:
            self.write('module')

        var_names = []
        discarded_names = []
        for name in node.names:
            if isinstance(name, tuple):
                name, alias = name
            else:
                alias = name
            self.writeline('l_%s = getattr(included_template, '
                           '%r, missing)' % (alias, name))
            self.writeline('if l_%s is missing:' % alias)
            self.indent()
            self.writeline('l_%s = environment.undefined(%r %% '
                           'included_template.__name__, '
                           'name=%r)' %
                           (alias, 'the template %%r (imported on %s) does '
                           'not export the requested name %s' % (
                                self.position(node),
                                repr(name)
                           ), name))
            self.outdent()
            if frame.toplevel:
                var_names.append(alias)
                if not alias.startswith('_'):
                    discarded_names.append(alias)
            frame.assigned_names.add(alias)

        if var_names:
            if len(var_names) == 1:
                name = var_names[0]
                self.writeline('context.vars[%r] = l_%s' % (name, name))
            else:
                self.writeline('context.vars.update({%s})' % ', '.join(
                    '%r: l_%s' % (name, name) for name in var_names
                ))
        if discarded_names:
            if len(discarded_names) == 1:
                self.writeline('context.exported_vars.discard(%r)' %
                               discarded_names[0])
            else:
                self.writeline('context.exported_vars.difference_'
                               'update((%s))' % ', '.join(imap(repr, discarded_names)))
Пример #9
0
    def __init__(self, names=(), message=None):
        if message is None:
            from jinja2.runtime import Undefined

            parts = []

            for name in names:
                if isinstance(name, Undefined):
                    parts.append(name._undefined_message)
                else:
                    parts.append(name)

            message = u'none of the templates given were found: ' + \
                      u', '.join(imap(text_type, parts))
        TemplateNotFound.__init__(self, names and names[-1] or None, message)
        self.templates = list(names)
Пример #10
0
def do_sum(environment, iterable, attribute=None, start=0):
    """Returns the sum of a sequence of numbers plus the value of parameter
    'start' (which defaults to 0).  When the sequence is empty it returns
    start.

    It is also possible to sum up only certain attributes:

    .. sourcecode:: jinja

        Total: {{ items|sum(attribute='price') }}

    .. versionchanged:: 2.6
       The `attribute` parameter was added to allow suming up over
       attributes.  Also the `start` parameter was moved on to the right.
    """
    if attribute is not None:
        iterable = imap(make_attrgetter(environment, attribute), iterable)
    return sum(iterable, start)
Пример #11
0
 def debug_info(self):
     """The debug info mapping."""
     return [tuple(imap(int, x.split('='))) for x in
             self._debug_info.split('&')]
Пример #12
0
def unicode_join(seq):
    """Simple args to unicode conversion and concatenation."""
    return concat(imap(text_type, seq))
Пример #13
0
 def __init__(self, names=(), message=None):
     if message is None:
         message = u'none of the templates given were found: ' + \
                   u', '.join(imap(text_type, names))
     TemplateNotFound.__init__(self, names and names[-1] or None, message)
     self.templates = list(names)
Пример #14
0
def unicode_join(seq):
    """Simple args to unicode conversion and concatenation."""
    return concat(imap(text_type, seq))
Пример #15
0
 def debug_info(self):
     """The debug info mapping."""
     return [tuple(imap(int, x.split("="))) for x in self._debug_info.split("&")]
Пример #16
0
    def visit_FromImport(self, node, frame):
        """
        FIX:
        Double `await` for "environment.get_template()._get_default_module_async()"
        """
        self.newline(node)

        if self.environment.is_async:
            self.write(
                "included_template = await (await environment.get_template(")
            self.visit(node.template, frame)
            self.write(", %r))." % self.name)
        else:
            self.write("included_template = environment.get_template(")
            self.visit(node.template, frame)
            self.write(", %r)." % self.name)

        if node.with_context:
            self.write("make_module%s(context.get_all(), True, %s)" % (
                self.environment.is_async and "_async" or "",
                self.dump_local_context(frame),
            ))
        elif self.environment.is_async:
            self.write("_get_default_module_async()")
        else:
            self.write("_get_default_module()")

        var_names = []
        discarded_names = []
        for name in node.names:
            if isinstance(name, tuple):
                name, alias = name
            else:
                alias = name
            self.writeline("%s = getattr(included_template, "
                           "%r, missing)" % (frame.symbols.ref(alias), name))
            self.writeline("if %s is missing:" % frame.symbols.ref(alias))
            self.indent()
            self.writeline("%s = undefined(%r %% "
                           "included_template.__name__, "
                           "name=%r)" % (
                               frame.symbols.ref(alias),
                               "the template %%r (imported on %s) does "
                               "not export the requested name %s" %
                               (self.position(node), repr(name)),
                               name,
                           ))
            self.outdent()
            if frame.toplevel:
                var_names.append(alias)
                if not alias.startswith("_"):
                    discarded_names.append(alias)

        if var_names:
            if len(var_names) == 1:
                name = var_names[0]
                self.writeline("context.vars[%r] = %s" %
                               (name, frame.symbols.ref(name)))
            else:
                self.writeline("context.vars.update({%s})" %
                               ", ".join("%r: %s" %
                                         (name, frame.symbols.ref(name))
                                         for name in var_names))
        if discarded_names:
            if len(discarded_names) == 1:
                self.writeline("context.exported_vars.discard(%r)" %
                               discarded_names[0])
            else:
                self.writeline("context.exported_vars.difference_"
                               "update((%s))" %
                               ", ".join(imap(repr, discarded_names)))