Source

django-swingcms / swingcms / custodian / templatetags / custodian_tags_and_filters.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from django import template

register = template.Library()


#######################################
##              FILTERS               #
#######################################

# TO-DO

#######################################
##               TAGS                 #
#######################################


class IfPermNode(template.Node):

    def __init__(self, action, object_, perms, nodelist_true, nodelist_false):

        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.action = action
        self.object = object_
        self.perms = perms

    def render(self, context):

        if (self.action, self.object) in template.resolve_variable(self.perms, context):
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

@register.tag('ifperm')
def ifperm(parser, token):
    """
    Load tags:

        {% load custodian_tags_and_filters %}

    Permission check:

        {% ifperm 'action' 'object' in perms %}
            ...
        {% else %}
            ...
        {% endifperm %}

    * in the example perms is a context variable
      and 'object' is optional as in global permission case
    """
    # get and check arguments
    bits = list(token.split_contents())
    if len(bits) == 4: # global permission
        __, action, op, perms = bits
        object_ = 'None'
    elif len(bits) == 5: # other permission
        __, action, object_, op, perms = bits
    else:
        raise template.TemplateSyntaxError(_("Wrong arguments numerosity."))

    # normalize args
    action = action.strip('"').strip("'")
    object_ = object_.strip('"').strip("'")
    if object_ == 'None': object_ = None

    # parse if else nodes
    end_tag = 'endifperm'
    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return IfPermNode(action, object_, perms, nodelist_true, nodelist_false)