예제 #1
0
def load_component(parser, token):
    parts = token.split_contents()
    if len(parts) <= 1:
        raise tmp.TemplateSyntaxError("'%s' needs a component key" % parts[0])

    # compile_filter is an undocumented django function that extracts
    # items from the "filter style" django syntax
    component_key = parser.compile_filter(parts[1])

    kwargs = {}

    parts = parts[2:]
    if len(parts):
        for part in parts:
            match = tmp.kwarg_re.match(part)
            if not match:
                raise tmp.TemplateSyntaxError("Malformed arguments to url tag")
            name, value = match.groups()
            if name:
                kwargs[name] = parser.compile_filter(value)
            else:
                raise BaseException(
                    "load_component can't accept args, only kwargs")

    return ComponentNode(component_key, kwargs)
예제 #2
0
def setcontext(parser, token):
    """
    Sets (updates) current template context with the rendered output of the block inside tags.

    This is useful when some template tag does not support storing its output in the context itself
    or we need some complex content (like language, user or URL dependent content) multiple times.

    Example usage::

        {% setcontext as varname %}
            {% complextag %}
        {% endsetcontext %}
    """

    nodelist = parser.parse(('endsetcontext', ))
    args = list(token.split_contents())

    if len(args) != 3 or args[1] != "as":
        raise base.TemplateSyntaxError(
            "'%s' tag takes 2 arguments and the first argument must be 'as'" %
            args[0])
    variable = args[2]

    parser.delete_first_token()

    return SetContextNode(nodelist, variable)
예제 #3
0
def genus_link(genus):
    if not isinstance(genus, Genus):
        raise template.TemplateSyntaxError(
            "genus_link tag requires a single Genus as argument")
    if genus.taxa.filter(goorchidtaxon__ready_for_display=True).count():
        return '<a href="%s">%s</a>' % (reverse('site-genus',
                                                args=[genus.slug]), genus.name)
    else:
        return genus.name
예제 #4
0
def species_link(species):
    if not isinstance(species, Taxon):
        raise template.TemplateSyntaxError(
            "species_link tag requires a single Taxon as argument")
    species = getattr(species, 'goorchidtaxon', species)
    is_ready = getattr(species, 'ready_for_display', False)
    if is_ready:
        return '<a href="%s">%s</a>' % (reverse(
            'site-species', args=[species.genus.slug, species.epithet
                                  ]), species.scientific_name)
    else:
        return species.scientific_name
예제 #5
0
def optional_assignment_tag(func=None, takes_context=None, name=None):
    """
    https://groups.google.com/forum/?fromgroups=#!topic/django-developers/E0XWFrkRMGc
    new template tags type
    """
    def dec(func):
        params, varargs, varkw, defaults = getargspec(func)

        class AssignmentNode(base.TagHelperNode):
            def __init__(self, takes_context, args, kwargs, target_var=None):
                super(AssignmentNode, self).__init__(takes_context, args,
                                                     kwargs)
                self.target_var = target_var

            def render(self, context):
                resolved_args, resolved_kwargs = self.get_resolved_arguments(
                    context)
                output = func(*resolved_args, **resolved_kwargs)
                if self.target_var is None:
                    return output
                else:
                    context[self.target_var] = output
                return ''

        function_name = (name or getattr(func, '_decorated_function',
                                         func).__name__)

        def compile_func(parser, token):
            bits = token.split_contents()[1:]
            if len(bits) < 2 or bits[-2] != 'as':
                target_var = None
            else:
                target_var = bits[-1]
                bits = bits[:-2]
            args, kwargs = base.parse_bits(parser, bits, params, varargs,
                                           varkw, defaults, takes_context,
                                           function_name)
            return AssignmentNode(takes_context, args, kwargs, target_var)

        compile_func.__doc__ = func.__doc__
        register.tag(function_name, compile_func)
        return func

    if func is None:
        # @register.assignment_tag(...)
        return dec
    elif callable(func):
        # @register.assignment_tag
        return dec(func)
    else:
        raise base.TemplateSyntaxError(
            "Invalid arguments provided to assignment_tag")
예제 #6
0
def admin_footer(parser, token):
    """
    Template tag that renders the footer information based on the
    authenticated user's permissions.
    """
    # split_contents() doesn't know how to split quoted strings.
    tag_name = token.split_contents()

    if len(tag_name) > 1:
        raise base.TemplateSyntaxError(
            '{} tag does not accept any argument(s): {}'.format(
                token.contents.split()[0],
                ', '.join(token.contents.split()[1:])))

    return AdminFooterNode()
예제 #7
0
def taxon_edits(taxon):
    if not isinstance(taxon, Taxon):
        raise template.TemplateSyntaxError(
            "taxon_edits tag requires a single Taxon as argument")
    edits = Edit.objects.filter(
        coordinate1=taxon.scientific_name,
        itemtype='character-value').order_by('-datetime')

    end = timezone.now()
    start = end - timedelta(7)
    edits = edits.filter(datetime__range=[start, end])
    if not edits:
        return '<p>No recent edits</p>'

    rows = []
    for i, edit in enumerate(edits):
        character_link = character_edit_link(edit.coordinate2)
        rows.append(
            BASE_ROW.format(date=edit.datetime,
                            author=escape(edit.author),
                            old_value=format_old_value(edit.old_value),
                            coord=character_link,
                            row_class=i % 2 and 'even' or 'odd'))
    return BASE_TABLE % ('Character', u'\n'.join(rows))