Esempio n. 1
0
def do_with(parser, token):
    """
    Adds one or more values to the context (inside of this block) for caching
    and easy access.

    For example::

        {% with total=person.some_sql_method %}
            {{ total }} object{{ total|pluralize }}
        {% endwith %}

    Multiple values can be added to the context::

        {% with foo=1 bar=2 %}
            ...
        {% endwith %}

    The legacy format of ``{% with person.some_sql_method as total %}`` is
    still accepted.
    """
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable "
                                  "assignment" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" %
                                  (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endwith', ))
    parser.delete_first_token()
    return WithNode(None, None, nodelist, extra_context=extra_context)
Esempio n. 2
0
    def parse(cls, parser, token):
        bits = token.split_contents()
        tagname = bits.pop(0)
        if len(bits) < 1:
            raise TemplateSyntaxError(
                "{tagname!r} requires at least one argument.".format(
                    tagname=tagname))
        field = bits.pop(0)
        if bits:
            if bits[0] == 'with':
                bits.pop(0)
            arg_dict = token_kwargs(bits, parser, support_legacy=False)

            # Validate against spaces around the '='.
            has_lonely_equal_sign = any(
                bit.startswith('=') or bit.endswith('=') for bit in bits)
            if has_lonely_equal_sign:
                # If '=' is leading/trailing or is the own char in the token,
                # then the user has used spaces around it. We can use a
                # distinct error message for this to aid the user.
                raise TemplateSyntaxError(
                    "In the {tagname} tag, "
                    "you must not put spaces around the '='. "
                    "For example, do label='value', not label = 'value'."
                    ".".format(tagname=tagname))
        else:
            arg_dict = {}
        if bits:
            raise TemplateSyntaxError(
                'Unknown argument for {tagname} tag: {bits!r}'.format(
                    tagname=tagname, bits=bits))
        return cls(field, arg_dict)
Esempio n. 3
0
 def parse(cls, parser, token):
     bits = token.split_contents()
     tagname = bits.pop(0)
     if len(bits) < 1:
         raise TemplateSyntaxError(
             "{tagname!r} requires at least one argument.".format(
                 tagname=tagname))
     field = bits.pop(0)
     if bits:
         with_ = bits.pop(0)
         if with_ != 'with':
             raise TemplateSyntaxError(
                 "{tagname}'s second argument must be 'with'.".format(
                     tagname=tagname))
         with_arguments = token_kwargs(bits, parser, support_legacy=False)
         if not with_arguments:
             raise TemplateSyntaxError(
                 "'with' in {tagname} tag needs at least one keyword "
                 "argument.".format(tagname=tagname))
     else:
         with_arguments = {}
     if bits:
         raise TemplateSyntaxError(
             'Unkown argument for {tagname} tag: {bits!r}'.format(
                 tagname=tagname,
                 bits=bits))
     return cls(field, with_arguments)
Esempio n. 4
0
    def parse(cls, parser, tokens):
        '''
        Renders a object in the current context. ::

            {% render object %} calls object.render(context)

        You can set some extra context with the 'with' argument::

            {% render object with value=1 %}
        '''
        bits = tokens.split_contents()
        tag_name = bits.pop(0)
        if not bits or bits[0] == 'with':
            raise template.TemplateSyntaxError(
                u'%r tag requires at least one argument' % tag_name)
        renderable = parser.compile_filter(bits.pop(0))

        if bits and bits[0] == 'with':
            bits.pop(0)
            arguments = token_kwargs(bits, parser, support_legacy=False)
            if not arguments:
                raise template.TemplateSyntaxError(
                    '"with" in %s tag needs at least one keyword argument.' %
                    tag_name)
            with_variables = arguments
        else:
            with_variables = {}

        return cls(renderable, with_variables)
Esempio n. 5
0
    def parse(cls, parser, token):
        bits = token.split_contents()
        tagname = bits.pop(0)
        if len(bits) < 1:
            raise TemplateSyntaxError(
                "{tagname!r} requires at least one argument.".format(
                    tagname=tagname))
        field = bits.pop(0)
        if bits:
            if bits[0] == 'with':
                bits.pop(0)
            arg_dict = token_kwargs(bits, parser, support_legacy=False)

            # Validate against spaces around the '='.
            has_lonely_equal_sign = any(
                bit.startswith('=') or bit.endswith('=')
                for bit in bits)
            if has_lonely_equal_sign:
                # If '=' is leading/trailing or is the own char in the token,
                # then the user has used spaces around it. We can use a
                # distinct error message for this to aid the user.
                raise TemplateSyntaxError(
                    "In the {tagname} tag, "
                    "you must not put spaces around the '='. "
                    "For example, do label='value', not label = 'value'."
                    ".".format(tagname=tagname))
        else:
            arg_dict = {}
        if bits:
            raise TemplateSyntaxError(
                'Unknown argument for {tagname} tag: {bits!r}'.format(
                    tagname=tagname,
                    bits=bits))
        return cls(field, arg_dict)
Esempio n. 6
0
def font_awesome_icon(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(bits, parser, support_legacy=False)
    if not extra_context:
        raise TemplateSyntaxError(
            format_lazy('{bit} accepts one argument', bit=bits[0]))
Esempio n. 7
0
    def parse(cls, parser, token: Token):

        # here is how split_contents() works:

        # {% formfield player.f1 label="f1 label" %}
        # ...yields:
        # ['formfield', 'player.f1', 'label="f1 label"']

        # {% formfield player.f2 "f2 label with no kwarg" %}
        # ...yields:
        # ['formfield', 'player.f2', '"f2 label with no kwarg"']

        # handle where the user did {% formfield player.f label = "foo" %}
        token.contents = token.contents.replace('label = ', 'label=')
        bits = token.split_contents()
        tagname = bits.pop(0)
        if len(bits) < 1:
            raise TemplateSyntaxError(f"{tagname} requires the name of the field.")
        field_name = bits.pop(0)
        if bits[:1] == ['with']:
            bits.pop(0)
        arg_dict = token_kwargs(bits, parser, support_legacy=False)
        if bits:
            raise TemplateSyntaxError(f'Unused parameter to formfield tag: {bits[0]}')
        return cls(field_name, **arg_dict)
def do_include(parser, token):
    """
    A copy of Django's built-in {% include ... %} tag that uses our custom
    IncludeNode to allow us to load dummy context for the pattern library.
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError(
            "%r tag takes at least one argument: the name of the template to "
            "be included." % bits[0])
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
    return IncludeNode(parser.compile_filter(bits[1]),
                       extra_context=namemap,
                       isolated_context=isolated_context)
    def __init__(self, parser, token):
        bits = token.split_contents()

        if len(bits) == 0:
            raise TemplateSyntaxError(
                "%r received invalid args, expected one element for render. Got: %r" %
                (bits[0], bits[1:]))

        remaining_bits = bits[2:]

        self.kwargs = token_kwargs(remaining_bits, parser)

        if remaining_bits:
            raise TemplateSyntaxError("%r received an invalid token: %r" %
                                      (bits[0], remaining_bits[0]))

        for key in self.kwargs:
            if key not in ('template', 'widget'):
                raise TemplateSyntaxError("%r received an invalid key: %r" %
                                          (bits[0], key))

            self.kwargs[key] = self.kwargs[key]

        self.nodelist = parser.parse(('end{}'.format(bits[0]),))
        parser.delete_first_token()

        self.element = Variable(bits[1])
def do_include(parser, token):
    """
    Same as core function, with construct_relative_path call
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included."
            % bits[0]
        )
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    bits[1] = construct_relative_path(parser.template_name, bits[1])

    return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap,
                       isolated_context=isolated_context)
Esempio n. 11
0
def do_with(parser, token):
    """
    Adds one or more values to the context (inside of this block) for caching
    and easy access.

    For example::

        {% with total=person.some_sql_method %}
            {{ total }} object{{ total|pluralize }}
        {% endwith %}

    Multiple values can be added to the context::

        {% with foo=1 bar=2 %}
            ...
        {% endwith %}

    The legacy format of ``{% with person.some_sql_method as total %}`` is
    still accepted.
    """
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable "
                                  "assignment" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" %
                                  (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endwith',))
    parser.delete_first_token()
    return WithNode(None, None, nodelist, extra_context=extra_context)
def accordion(parser, token):
    kwargs = token_kwargs(token.split_contents()[1:], parser)
    if not kwargs.get('name'):
        raise template.TemplateSyntaxError('accordion requires name argument')
    node_list = parser.parse(('endaccordion', ))
    parser.delete_first_token()
    return AccordionNode(node_list, **kwargs)
def do_include(parser, token):
    """
    Same as core function, with construct_relative_path call
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("%r tag takes at least one argument: "
                                  "the name of the template to be included." %
                                  bits[0])
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    bits[1] = construct_relative_path(parser.template_name, bits[1])

    return IncludeNode(parser.compile_filter(bits[1]),
                       extra_context=namemap,
                       isolated_context=isolated_context)
    def __init__(self, parser, token):
        bits = token.split_contents()

        if len(bits) == 0:
            raise TemplateSyntaxError(
                "%r received invalid args, expected one element for render. Got: %r" %
                (bits[0], bits[1:]))

        remaining_bits = bits[2:]

        self.kwargs = token_kwargs(remaining_bits, parser)

        if remaining_bits:
            raise TemplateSyntaxError("%r received an invalid token: %r" %
                                      (bits[0], remaining_bits[0]))

        for key in self.kwargs:
            if key not in ('template', 'widget'):
                raise TemplateSyntaxError("%r received an invalid key: %r" %
                                          (bits[0], key))

            self.kwargs[key] = self.kwargs[key]

        self.nodelist = parser.parse(('end{}'.format(bits[0]),))
        parser.delete_first_token()

        self.element = Variable(bits[1])
Esempio n. 15
0
def clarity(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    if len(remaining_bits) < 1:
        raise TemplateSyntaxError('This tag requires at least one argument')
    tags = token_kwargs(remaining_bits, parser, support_legacy=False)
    return SimpleAnalyticNode(tags)
Esempio n. 16
0
def extend(parser, token):
    '''
    Extends another template, passing additional variables to the parent.
    '''
    bits = token.split_contents()
    kwargs = token_kwargs(bits[2:], parser)
    token.contents = " ".join(bits[:2])
    return ExtendNode(do_extends(parser, token), kwargs)
Esempio n. 17
0
def do_tenant(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)

    nodelist = parser.parse(("endtenant",))
    parser.delete_first_token()
    return TenantNode(nodelist, tenant_var=remaining_bits[0])
def accordionsection(parser, token):
    kwargs = token_kwargs(token.split_contents()[1:], parser)
    if 'heading' not in kwargs:
        raise template.TemplateSyntaxError(
            'accordion section requires heading argument')
    node_list = parser.parse(('endaccordionsection', ))
    parser.delete_first_token()
    return AccordionSectionNode(node_list, **kwargs)
Esempio n. 19
0
def template_variable(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=False)
    if not extra_context:
        raise TemplateSyntaxError(
            f"'{bits[0]}' expects at least one key word variable")
    return MacroNode(remaining_bits, extra_context=extra_context)
Esempio n. 20
0
def extend(parser, token):
    '''
    Extends another template, passing additional variables to the parent.
    '''
    bits = token.split_contents()
    kwargs = token_kwargs(bits[2:], parser)
    token.contents = " ".join(bits[:2])
    return ExtendNode(do_extends(parser, token), kwargs)
Esempio n. 21
0
def get_kwargs(parser, token):
    """helper for parsing token kwargs"""
    kwargs = {}
    bits = token.split_contents()
    bits = bits[1:]
    if len(bits):
        kwargs = token_kwargs(bits, parser)
    return kwargs
Esempio n. 22
0
    def __init__(self, tag_name, parser, token):
        self.tag_name = tag_name

        bits = token.split_contents()[1:]
        self.kwargs = {k: v.var for k, v in token_kwargs(bits, parser).items()}

        nodelist = parser.parse(('end{0}'.format(tag_name), ))
        parser.delete_first_token()
        self.nodelist = nodelist
Esempio n. 23
0
def script(parser, token):
    # Parse out any keyword args
    token_args = token.split_contents()
    kwargs = token_kwargs(token_args[1:], parser)

    nodelist = parser.parse(('endscript', ))
    parser.delete_first_token()

    return NonceScriptNode(nodelist, **kwargs)
Esempio n. 24
0
    def __init__(self, tag_name, parser, token):
        self.tag_name = tag_name

        bits = token.split_contents()[1:]
        self.kwargs = {k: v.var for k,v in token_kwargs(bits, parser).items()}

        nodelist = parser.parse(('end{0}'.format(tag_name),))
        parser.delete_first_token()
        self.nodelist = nodelist
Esempio n. 25
0
def script(parser, token):
    # Parse out any keyword args
    token_args = token.split_contents()
    kwargs = token_kwargs(token_args[1:], parser)

    nodelist = parser.parse(('endscript',))
    parser.delete_first_token()

    return NonceScriptNode(nodelist, **kwargs)
Esempio n. 26
0
def icon(parser, token):
	bits = token.split_contents()
	if len(bits) < 2:
		raise TemplateSyntaxError("'%s' requires at least one argument." % bits[0])
	name = parser.compile_filter(bits[1])
	remaining_bits = bits[2:]
	extra_context = token_kwargs(remaining_bits, parser)
	if remaining_bits:
		raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
	return IconNode(name=name, extra_context=extra_context)
Esempio n. 27
0
def icon(parser, token):
	bits = token.split_contents()
	if len(bits) < 2:
		raise TemplateSyntaxError("'%s' requires at least one argument." % bits[0])
	name = parser.compile_filter(bits[1])
	remaining_bits = bits[2:]
	extra_context = token_kwargs(remaining_bits, parser)
	if remaining_bits:
		raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
	return IconNode(name=name, extra_context=extra_context)
Esempio n. 28
0
def _if_feature(parser, token, enabled_first):
    """Common implementation for feature-based if statements.

    This constructs a :py:class:`IfFeatureNode` for the consuming template tag,
    allowing for "if" and "if not" checks.

    Args:
        parser (django.template.Parser):
            The parser being used to parse this template tag.

        token (django.template.Token):
            The token representing this template tag.

        enabled_first (bool):
            If ``True``, this behaves as an "if enabled" check.
            If ``False``, this behaves as a "if disabled' check.

    Returns:
        IfFeatureNode:
        The feature checker node to use for the template.
    """
    bits = token.split_contents()
    tag = bits[0]
    end_tag = 'end%s' % tag

    if len(bits) < 2:
        raise TemplateSyntaxError('%r requires a feature ID argument'
                                  % tag)

    nodelist_1 = parser.parse(('else', end_tag))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_2 = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_2 = NodeList()

    if enabled_first:
        nodelist_enabled = nodelist_1
        nodelist_disabled = nodelist_2
    else:
        nodelist_disabled = nodelist_1
        nodelist_enabled = nodelist_2

    feature_id = parser.compile_filter(bits[1])
    remaining_bits = bits[2:]
    extra_kwargs = token_kwargs(remaining_bits, parser)

    if remaining_bits:
        raise TemplateSyntaxError('%r received an invalid token: %r'
                                  % (tag, remaining_bits[0]))

    return IfFeatureNode(nodelist_enabled, nodelist_disabled, feature_id,
                         extra_kwargs)
Esempio n. 29
0
def do_card(
    parser,
    token,
):
    nodelist = parser.parse(('endcard', ))
    parser.delete_first_token()
    bits = token.split_contents()
    tagname = bits.pop(0)
    arg_dict = token_kwargs(bits, parser)

    return CardNode(nodelist, **arg_dict)
Esempio n. 30
0
def do_form_renderer(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("%r tag takes at least one argument: the form that will be rendered" % bits[0])
    remaining_bits = bits[2:]
    options = token_kwargs(remaining_bits, parser, support_legacy=False)
    template_name = options.get("template", parser.compile_filter("'forms/default_form.html'"))
    options["use_csrf"] = options.get("use_csrf", parser.compile_filter("True"))
    options["form"] = parser.compile_filter(bits[1])
    options["method"] = options.get("method", parser.compile_filter("'POST'"))
    return SnippetsIncludeNode(template_name, extra_context=options)
Esempio n. 31
0
def do_form_renderer(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("%r tag takes at least one argument: the form that will be rendered" % bits[0])
    remaining_bits = bits[2:]
    options = token_kwargs(remaining_bits, parser, support_legacy=False)
    template_name = options.get('template', parser.compile_filter("'is_core/forms/default_form.html'"))
    options['use_csrf'] = options.get('use_csrf', parser.compile_filter('True'))
    options['form'] = parser.compile_filter(bits[1])
    options['method'] = options.get('method', parser.compile_filter("'POST'"))
    return IncludeNode(template_name, extra_context=options)
Esempio n. 32
0
def collapse(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable assignment" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endcollapse',))
    parser.delete_first_token()
    return CollapseNode(nodelist, extra_context=extra_context)
Esempio n. 33
0
def collapse(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable assignment" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endcollapse',))
    parser.delete_first_token()
    return CollapseNode(nodelist, extra_context=extra_context)
Esempio n. 34
0
def impressions_for_cart(parser, token):
    """
    {% analytics_impressions queryset=queryset brand="Nawoka" metrics="a b c" %}
    """
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=False)
    if not extra_context:
        raise TemplateSyntaxError(
            f"'{bits[0]}' expects at least one key word variable")
    return AnalyticsNode(extra_context=extra_context)
Esempio n. 35
0
 def __init__(self, parser, token):
     bits = token.split_contents()[1:]
     self.kwargs = token_kwargs(bits, parser)
     for key in self.kwargs:
         if key not in (
                 'key',
                 'templatename',
                 'text',
         ):
             raise TemplateSyntaxError(
                 "'table_sortlink' received invalid key: %s" % key)
Esempio n. 36
0
def do_form_renderer(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("%r tag takes at least one argument: the form that will be rendered" % bits[0])
    remaining_bits = bits[2:]
    options = token_kwargs(remaining_bits, parser, support_legacy=False)
    template_name = options.get('template', parser.compile_filter("'forms/default_form.html'"))
    options['use_csrf'] = options.get('use_csrf', parser.compile_filter('True'))
    options['form'] = parser.compile_filter(bits[1])
    options['method'] = options.get('method', parser.compile_filter("'POST'"))
    return SnippetsIncludeNode(template_name, extra_context=options)
Esempio n. 37
0
def urlquerify(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]

    update_items = token_kwargs(remaining_bits, parser, support_legacy=True)

    named_args = token_named_args(remaining_bits, ['remove', 'only'])
    remove_items = named_args.get('remove', '').split(',')
    only_items = named_args.get('only', '').split(',')

    return UrlquerifyNode(update_items, remove_items, only_items)
Esempio n. 38
0
def _if_feature(parser, token, enabled_first):
    """Common implementation for feature-based if statements.

    This constructs a :py:class:`IfFeatureNode` for the consuming template tag,
    allowing for "if" and "if not" checks.

    Args:
        parser (django.template.Parser):
            The parser being used to parse this template tag.

        token (django.template.Token):
            The token representing this template tag.

        enabled_first (bool):
            If ``True``, this behaves as an "if enabled" check.
            If ``False``, this behaves as a "if disabled' check.

    Returns:
        IfFeatureNode:
        The feature checker node to use for the template.
    """
    bits = token.split_contents()
    tag = bits[0]
    end_tag = 'end%s' % tag

    if len(bits) < 2:
        raise TemplateSyntaxError('%r requires a feature ID argument' % tag)

    nodelist_1 = parser.parse(('else', end_tag))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_2 = parser.parse((end_tag, ))
        parser.delete_first_token()
    else:
        nodelist_2 = NodeList()

    if enabled_first:
        nodelist_enabled = nodelist_1
        nodelist_disabled = nodelist_2
    else:
        nodelist_disabled = nodelist_1
        nodelist_enabled = nodelist_2

    feature_id = parser.compile_filter(bits[1])
    remaining_bits = bits[2:]
    extra_kwargs = token_kwargs(remaining_bits, parser)

    if remaining_bits:
        raise TemplateSyntaxError('%r received an invalid token: %r' %
                                  (tag, remaining_bits[0]))

    return IfFeatureNode(nodelist_enabled, nodelist_disabled, feature_id,
                         extra_kwargs)
Esempio n. 39
0
def foundation_form(parser, token):
    '''
    Renders a form with Foundation markup.
    '''
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError('Incorrect number of arguements for %s, Form object required' % bits[0])
    form = parser.compile_filter(bits[1])
    kwargs = token_kwargs(bits[2:], parser)
    nodelist = parser.parse(('end_foundation_form',))
    parser.delete_first_token()
    return FoundationFormNode(form, nodelist, **kwargs)
Esempio n. 40
0
def do_component(parser, token):
    """
        {% component_block "name" variable="value" variable2="value2" ... %}
    """

    bits = token.split_contents()

    tag_args, tag_kwargs = parse_bits(
        parser=parser,
        bits=bits,
        params=["tag_name", "component_name"],
        takes_context=False,
        name="component_block",
        **PARSE_BITS_DEFAULTS
    )
    tag_name = tag_args.pop(0)

    if len(bits) < 2:
        raise TemplateSyntaxError(
            "Call the '%s' tag with a component name as the first parameter" % tag_name
        )

    component_name = bits[1]
    if not component_name.startswith(('"', "'")) or not component_name.endswith(
        ('"', "'")
    ):
        raise TemplateSyntaxError(
            "Component name '%s' should be in quotes" % component_name
        )

    component_name = component_name.strip('"\'')
    component_class = registry.get(component_name)
    component = component_class()

    extra_context = {}
    if len(bits) > 2:
        extra_context = component.context(**token_kwargs(bits[2:], parser))

    slots_filled = NodeList()
    tag_name = bits[0]
    while tag_name != "endcomponent_block":
        token = parser.next_token()
        if token.token_type != TokenType.BLOCK:
            continue

        tag_name = token.split_contents()[0]

        if tag_name == "slot":
            slots_filled += do_slot(parser, token, component=component)
        elif tag_name == "endcomponent_block":
            break

    return ComponentNode(component, extra_context, slots_filled)
Esempio n. 41
0
def cinclude(parser, token):
    """
    Loads a template and renders it with the current context. You can pass
    additional context using keyword arguments. This is bascially a enhanced
    version of the base django {% include filter %}. The difference is, that
    this tag is client template aware and will look into client template
    directories before falling back to django's standard loading.

    Example::

        {% cinclude "foo/some_include" %}
        {% cinclude "foo/some_include" with bar="BAZZ!" baz="BING!" %}

    Use the ``only`` argument to exclude the current context when rendering
    the included template::

        {% cinclude "foo/some_include" only %}
        {% cinclude "foo/some_include" with bar="1" only %}
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: the name of the template to "
            "be included." % bits[0])
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    path = bits[1]
    if path[0] in ('"', "'") and path[-1] == path[0]:
        return ClientIncludeNode(
            path[1:-1], extra_context=namemap,
            isolated_context=isolated_context)
    return ClientIncludeNode(
        parser.compile_filter(
            bits[1]), extra_context=namemap, isolated_context=isolated_context)
Esempio n. 42
0
def do_embed(parser, token):
    """{% embed %} template tag. Allows to include a template and optionally override its slots, in a similar fashion
    to block tags in extended templates.

    Example::

        {% embed 'section.html' %}
            {% slot title %}<h1>Title</h1>{% endslot %}
            {% slot content %}<p>Content</p>{% endslot %}
        {% endembed %}

    You may use the ``only`` argument and keyword arguments using ``with`` like when using ``{% include %}``
    """

    # Exact copy from do_include_node()
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError(
            "%r tag takes at least one argument: the name of the template to "
            "be included." % bits[0])
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError("The %r option was specified more "
                                      "than once." % option)
        if option == "with":
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          "one keyword argument." % bits[0])
        elif option == "only":
            value = True
        else:
            raise TemplateSyntaxError(
                f"Unknown argument for {bits[0]!r} tag: {option!r}.")
        options[option] = value
    isolated_context = options.get("only", False)
    namemap = options.get("with", {})
    bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
    # End exact copy from do_include_node()

    nodelist = parser.parse(("endembed", ))
    parser.delete_first_token()

    return EmbedNode(
        parser.compile_filter(bits[1]),
        nodelist,
        extra_context=namemap,
        isolated_context=isolated_context,
    )
Esempio n. 43
0
def do_html_widget(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable assignment" % bits[0])
    if not 'id' in extra_context or not 'class' in extra_context:
        raise TemplateSyntaxError("id and class parameters are required")
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endwidget',))
    parser.delete_first_token()
    return HtmlWidgetNode("widgets/widget.html", None, None, nodelist, extra_context=extra_context)
Esempio n. 44
0
def do_html_widget(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not extra_context:
        raise TemplateSyntaxError("%r expected at least one variable assignment" % bits[0])
    if not 'id' in extra_context or not 'class' in extra_context:
        raise TemplateSyntaxError("id and class parameters are required")
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0]))
    nodelist = parser.parse(('endwidget',))
    parser.delete_first_token()
    return HtmlWidgetNode("widgets/widget.html", None, None, nodelist, extra_context=extra_context)
Esempio n. 45
0
def transpiling_block(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    options = token_kwargs(remaining_bits, parser, support_legacy=True)
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" %
                                  (bits[0], remaining_bits[0]))

    nodelist = parser.parse(('endpostcssmodules', ))
    parser.delete_first_token()
    return TranspilingNode(nodelist,
                           options=options,
                           path=f'{parser.origin.name}.{token.lineno}.cssm')
Esempio n. 46
0
 def __init__(self, parser, token):
     bits = token.split_contents()[1:]
     self.kwargs = token_kwargs(bits, parser)
     for key in self.kwargs:
         if key not in (
                 'view',
                 'args',
                 'classname',
                 'text',
                 'addnextparam',
         ):
             raise TemplateSyntaxError(
                 "'tablerowaction' received invalid key: %s" % key)
Esempio n. 47
0
def oauth2_authorize(parser, token):
    bits = token.contents.split()
    remaining_bits = bits[1:]
    params = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not params or not ('redirect_uri' in params and 'callback' in params 
                          and 'elem_id' in params):
        raise TemplateSyntaxError(
            "%r expected at least three variables namely: "
            "'elem_id', 'redirect_uri' and 'callback'" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" %
                                  (bits[0], remaining_bits[0]))
    return AuthorizeNode(params)
Esempio n. 48
0
def wepay_oauth2(parser, token):
    bits = token.contents.split()
    remaining_bits = bits[1:]
    params = token_kwargs(remaining_bits, parser, support_legacy=True)
    if not params or not ('redirect_uri' in params and 'callback' in params
                          and 'elem_id' in params):
        raise TemplateSyntaxError(
            "%r expected at least three variables namely: "
            "'elem_id', 'redirect_uri' and 'callback'" % bits[0])
    if remaining_bits:
        raise TemplateSyntaxError("%r received an invalid token: %r" %
                                  (bits[0], remaining_bits[0]))
    return AuthorizeNode(params)
Esempio n. 49
0
def _do_include(parser, token, _class):
	"""
    Loads a template and renders it with the current context. You can pass
    additional context using keyword arguments.

    Example::

        {% include "foo/some_include" %}
        {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %}

    Use the ``only`` argument to exclude the current context when rendering
    the included template::

        {% include "foo/some_include" only %}
        {% include "foo/some_include" with bar="1" only %}
	"""
	bits = token.split_contents()
	if len(bits) < 2:
		raise TemplateSyntaxError("%r tag takes at least one argument: the name of the template to be included." % bits[0])
	options = {}
	remaining_bits = bits[2:]
	template_type = None
	while remaining_bits:
		option = remaining_bits.pop(0)
		if option in options:
			raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)

		if option == 'with':
			value = token_kwargs(remaining_bits, parser, support_legacy=False)
			if not value:
				raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
		elif option == 'only':
			value = True
		elif option[:4] == 'type':
			template_type = option[5:]
			continue
		else:
			raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
		options[option] = value
	isolated_context = options.get('only', False)
	namemap = options.get('with', {})

	template_filename = str(bits[1]).replace("'", '').replace('"', '')
	if not template_type:
		template_type = template_filename.split('.')[-1]

	return _class(template_type, template_filename, parser.compile_filter(bits[1]), extra_context=namemap,
                       isolated_context=isolated_context)
Esempio n. 50
0
def do_include(parser, token):
    """
    Loads a template and renders it with the current context, if it exists.
    You can pass additional context using keyword arguments.

    Example::

        {% optional_include "foo/some_include" %}
        {% optional_include "foo/some_include" with bar="BAZZ!" baz="BING!" %}

    Use the ``only`` argument to exclude the current context when rendering
    the included template::

        {% optional_include "foo/some_include" only %}
        {% optional_include "foo/some_include" with bar="1" only %}
    """
    bits = token.split_contents()
    if len(bits) < 2:
        msg = (
            "%r tag takes at least one argument: the name of the template "
            "to be optionally included."
        ) % bits[0]
        raise TemplateSyntaxError(msg)
    options = {}
    remaining_bits = bits[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    node = OptionalIncludeNode(
        parser.compile_filter(bits[1]),
        extra_context=namemap,
        isolated_context=isolated_context,
    )
    return node
Esempio n. 51
0
def include_compressed(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError(
            "%r tag takes at least one argument: the name of the template to "
            "be included." % bits[0]
        )
    compress_types =  ['js', 'css', 'html']
    options = {}
    remaining_bits = bits[2:]

    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True

        elif option in compress_types:
            unused = compress_types.copy()
            unused.remove(option)
            for t in unused:
                options[t] = False
            value = True
            options['type'] = option

        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value

    if not "type" in options:
        TemplateSyntaxError("'html','css' or 'js' not specified "
                            "for %r tag." % bits[0])

    compress_type = options.get('type', 'html')
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})

    bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
    return CompressedIncludeNode(parser.compile_filter(bits[1]), extra_context=namemap,
                       isolated_context=isolated_context,
                       compress_type=compress_type)
Esempio n. 52
0
    def parse_with(cls, tagname, parser, bits, options):
        if bits:
            if bits[0] == "with":
                bits.pop(0)
                arguments = token_kwargs(bits, parser, support_legacy=False)
                if not arguments:
                    raise TemplateSyntaxError('"with" in %s tag needs at ' "least one keyword argument." % tagname)
                options["with"] = arguments
            elif bits[0] not in ("only",) and not cls.optional_with_parameter:
                raise TemplateSyntaxError("Unknown argument for %s tag: %r." % (tagname, bits[0]))

        if bits:
            if cls.accept_only_parameter and bits[0] == "only":
                bits.pop(0)
                options["only"] = True
def do_include(parser, token):
    """
    Loads a template and renders it with the current context. You can pass
    additional context using keyword arguments.

    Example::

        {% include "foo/some_include" "foo/some_other_include" %}
        {% include "foo/some_include" "foo/some_other_include" with bar="BAZZ!" baz="BING!" %}

    Use the ``only`` argument to exclude the current context when rendering
    the included template::

        {% include "foo/some_include" "foo/some_other_include" only %}
        {% include "foo/some_include" "foo/some_other_include" with bar="1" only %}
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("%r tag takes at least one argument: the name of the template to be included." % bits[0])
    options = {}

    remaining_bits = bits[1:]
    paths = []
    stop_markers = ('only', 'with')
    while remaining_bits and remaining_bits[0] not in stop_markers:
        paths.append(remaining_bits.pop(0))

    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError('The %r option was specified more '
                                      'than once.' % option)
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=False)
            if not value:
                raise TemplateSyntaxError('"with" in %r tag needs at least '
                                          'one keyword argument.' % bits[0])
        elif option == 'only':
            value = True
        else:
            raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
                                      (bits[0], option))
        options[option] = value
    isolated_context = options.get('only', False)
    namemap = options.get('with', {})
    template_names = [parser.compile_filter(path) for path in paths]
    return MultipleIncludeNode(template_names, extra_context=namemap,
                       isolated_context=isolated_context)
Esempio n. 54
0
    def parse(cls, parser, token):
        bits = token.split_contents()
        tagname = bits.pop(0)
        if len(bits) < 1:
            raise TemplateSyntaxError(
                "{tagname!r} requires at least one argument.".format(
                    tagname=tagname))
        field = bits.pop(0)
        if bits:
            with_ = bits.pop(0)
            if with_ != 'with':
                raise TemplateSyntaxError(
                    "{tagname}'s second argument must be 'with'.".format(
                        tagname=tagname))
            with_arguments = token_kwargs(bits, parser, support_legacy=False)

            # Validate against spaces around the '='.
            has_lonely_equal_sign = any(
                bit == '=' or bit.startswith('=') or bit.endswith('=')
                for bit in bits)
            if has_lonely_equal_sign:
                # If '=' is leading/trailing or is the own char in the token,
                # then the user has used spaces around it. We can use a
                # distinct error message for this to aid the user.
                raise TemplateSyntaxError(
                    "The keyword arguments after 'with' in {tagname} tag "
                    "must not contain spaces around the '='. "
                    "A keyword argument must be in the form of "
                    "{example}.".format(
                        tagname=tagname,
                        example='{% formfield ... with name="value" %}'))

            if not with_arguments:
                example = '{% formfield ... with name="value" %}'
                raise TemplateSyntaxError(
                    "'with' in {tagname} tag needs at least one keyword "
                    "argument. A keyword argument must be in the form of "
                    "{example}.".format(
                        tagname=tagname,
                        example=example))
        else:
            with_arguments = {}
        if bits:
            raise TemplateSyntaxError(
                'Unkown argument for {tagname} tag: {bits!r}'.format(
                    tagname=tagname,
                    bits=bits))
        return cls(field, with_arguments)
Esempio n. 55
0
def widget(parser, token):
    bits = token.split_contents()
    tag_name = bits.pop(0)

    try:
        widget = parser.compile_filter(bits.pop(0))
    except IndexError:
        raise template.TemplateSyntaxError('%s requires one positional argument' % tag_name)

    asvar = pop_asvar(bits)

    kwargs = token_kwargs(bits, parser)
    if bits:
        raise template.TemplateSyntaxError('%s accepts only one positional argument' % tag_name)

    return Widget(widget, kwargs, asvar)
Esempio n. 56
0
 def parse_with(cls, tagname, parser, bits, options):
     if bits:
         if bits[0] == 'with':
             bits.pop[0]
             arguments = token_kwargs(bits, parser, support_legacy=False)
             if not arguments:
                 raise TemplateSyntaxError('"with" in %s tag needs at '
                                           'least one keyword argument.' %
                                           tagname)
             options['with'] = arguments
         elif bits[0] not in ('only',) and not cls.optional_with_parameter:
             raise TemplateSyntaxError('Unknown argument for %s tag: %r.' %
                                       (tagname, bits[0]))
     if bits:
         if cls.accept_only_parameter and vits[0] == 'only':
             bits.pop(0)
             options['only'] = True
Esempio n. 57
0
def do_define(parser, token):
    bits = token.split_contents()[1:]
    initial_values = None

    if len(bits) < 3 and bits[1] != 'as':
        raise template.TemplateSyntaxError(error_message)

    del bits[1] # "as"

    try:
        variable_name, variable_type = bits[:2]
    except ValueError:
        raise TemplateSyntaxError(error_message)

    try:
        optional = bits[2] == 'optional'
    except IndexError:
        optional = False

    if not optional and 'optional' in bits:
        raise TemplateSyntaxError(error_message)

    try:
        if optional:
            index = 3
        else:
            index = 2

        with_tag = bits[index]
        assert with_tag, 'with'
        bits = bits[index + 1:]
    except IndexError:
        pass
    except AssertionError:
        raise TemplateSyntaxError(error_message)
    else:
        initial_values = token_kwargs(bits, parser, support_legacy=False)

        if not initial_values:
            raise TemplateSyntaxError(error_message)

        for var, val in initial_values.items():
            initial_values[var] = val.resolve({}) # nasty, don't have access to context.

    return DefineNode(variable_name, variable_type, optional, initial_values)
    def handle_token(cls, parser, token):
        bits = token.split_contents()
        attrs = {}

        if len(bits) < 2:
            raise template.TemplateSyntaxError("'%s' takes at least one argument (js module)" % bits[0])

        if len(bits) > 2:
            for bit in bits[2:]:
                # First we try to extract a potential kwarg from the bit
                kwarg = token_kwargs([bit], parser)
                if kwarg:
                    attrs.update(kwarg)
                else:
                    attrs[bit] = True  # for flatatt

        path = parser.compile_filter(bits[1])
        return cls(path, tag_attrs=attrs)
    def __init__(self, parser, token):
        bits = token.split_contents()
        remaining_bits = bits[1:]

        self.kwargs = token_kwargs(remaining_bits, parser)

        if remaining_bits:
            raise TemplateSyntaxError("%r received an invalid token: %r" %
                                      (bits[0], remaining_bits[0]))

        for key in self.kwargs:
            if key not in ('form', 'layout', 'template'):
                raise TemplateSyntaxError("%r received an invalid key: %r" %
                                          (bits[0], key))

            self.kwargs[key] = self.kwargs[key]

        self.nodelist = parser.parse(('end{}'.format(bits[0]),))
        parser.delete_first_token()