Пример #1
0
def if_like(parser, token):
    """
    Determine if a certain type of relationship exists between two users.
    The ``status`` parameter must be a slug matching either the from_slug,
    to_slug or symmetrical_slug of a RelationshipStatus.

    Example::

        {% if_like user object  %}
            messgae
        {% else %}
            Sorry coworkers
        {% endif_like %}
        
    """
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise TemplateSyntaxError, "%r takes 2 arguments:\n" % (bits[0], if_like.__doc__)
    object_expr = parser.compile_filter(bits[2])
    end_tag = 'end' + bits[0]
    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 IfLikeNode(nodelist_true, nodelist_false, bits[1], object_expr)
Пример #2
0
def testrule(parser, token):

#    args = token.contents.split()
#    if len(args) < 2:
#        raise TemplateSyntaxError("'testrule' tag requires at least a rule name.")
#
#    rule_name = args[1]
#    params = []
#    if len(args) > 2:
#        params = args[2:]
#
#    nodelist = parser.parse(('endtestrule',))
#    parser.delete_first_token()
#    return RuleTestNode(rule_name, params, nodelist)

    args = token.contents.split()
    if len(args) < 2:
        raise TemplateSyntaxError("'testrule' tag requires at least a rule name.")

    rule_name = args[1]
    params = []
    if len(args) > 2:
        params = args[2:]

#    bits = token.split_contents()[1:]
#    var = template.defaulttags.TemplateIfParser(parser, bits).parse()
    nodelist_true = parser.parse(('else', 'endtestrule'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endtestrule',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return RuleTestNode(rule_name, params, nodelist_true, nodelist_false)
def if_relationship(parser, token):
    """
    Determine if a certain type of relationship exists between two users.
    The ``status`` parameter must be a slug matching either the from_slug,
    to_slug or symmetrical_slug of a RelationshipStatus.

    Example::

        {% if_relationship from_user to_user "friends" %}
            Here are pictures of me drinking alcohol
        {% else %}
            Sorry coworkers
        {% endif_relationship %}

        {% if_relationship from_user to_user "blocking" %}
            damn seo experts
        {% endif_relationship %}
    """
    bits = list(token.split_contents())
    if len(bits) != 4:
        raise TemplateSyntaxError("%r takes 3 arguments:\n%s" % (bits[0], if_relationship.__doc__))
    end_tag = 'end' + bits[0]
    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 IfRelationshipNode(nodelist_true, nodelist_false, *bits[1:])
Пример #4
0
def do_ifinstalled(parser, token):
    """
    Outputs the contents of the block if the app is in INSTALLED_APPS

    Examples::

        {% ifinstalled "my.app" %}
            ...
        {% endifinstalled %}

        {% ifinstalled "my.app" %}
            ...
        {% else %}
            ...
        {% endifinstalled %}
    """
    bits = list(token.split_contents())
    if len(bits) != 2:
        raise TemplateSyntaxError("%r takes two arguments" % bits[0])
    end_tag = 'end' + bits[0]
    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 InstalledAppNode(bits[1][1:-1], nodelist_true, nodelist_false)
Пример #5
0
def if_row_perms(parser, token):
    '''If-style template tag to test if the specified user has the
        specified row-level perms for the specified object.

        Usage:
            {% load row_level_perms %}

            {% if_row_perms user 'perm' object %}
            You have permission!
            {% endif_row_perms %}

            {% if_row_perms user 'perm' object %}
            You have permission!
            {% else %}
            You don't have permission :(
            {% endif_row_perms %}
    '''
    tag, _, bits = token.contents.partition(' ')
    bits = bits.split()
    end_tag = 'end' + tag
    nodelist_true = parser.parse([end_tag, 'else'])
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse([end_tag])
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    if len(bits) < 3:
        raise template.TemplateSyntaxError, "%r tag requires exactly 3 arguments." % tag
    bits += [nodelist_true, nodelist_false]
    return PermNode(*bits)
Пример #6
0
def ifnotpermission(parser, token):
    """
    Usage:
      {% ifnotpermission [permission_type] [object] %}
        content
      {% else %}
        content
      {% endifnotpermission %}

    Calls the Permission.objects.[permission_type]() function with the current
    user and the given object.  If true, renders the contents of this tag.
    If false, renders nothing.
    """
    tokens = token.split_contents()
    tag_name, permission_type, object = tokens
    endtag = 'end' + tag_name

    # Strip the quotes off the ends of the permission_type string
    permission_type = _strip_quotes(permission_type)

    nodelist_true = parser.parse(('else', endtag))
    #parser.delete_first_token()
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse((endtag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    # NOTE: Since this is the NOT tag, nodelist_true and nodelist_false
    # are switched...
    return IfPermissionNode(nodelist_false, nodelist_true, permission_type,
                            object)
Пример #7
0
    def render(self, context):
        nodelist = template.NodeList()

        context.push()
        try:
            start = self.start.resolve(context)
        except template.VariableDoesNotExist:
            return ''
        except AttributeError:
            start = self.start

        try:
            end = self.end.resolve(context)
        except template.VariableDoesNotExist:
            return ''
        except AttributeError:
            end = self.end

        try:
            step = self.step.resolve(context)
        except template.VariableDoesNotExist:
            return ''
        except AttributeError:
            step = self.step

        for i in range(start, end, step):
            context[self.var_name] = i

            for node in self.nodelist_loop:
                nodelist.append(node.render(context))

        context.pop()
        return nodelist.render(context)
Пример #8
0
    def parse_blocks(self):
        """
        Parse template blocks for block tags.

        Example:
            {% a %} b {% c %} d {% e %} f {% g %}
             => pre_c: b
                pre_e: d
                pre_g: f
            {% a %} b {% f %}
             => pre_c: b
                pre_e: None
                pre_g: None
        """
        # if no blocks are defined, bail out
        if not self.options.blocks:
            return
        # copy the blocks
        blocks = deepcopy(self.options.blocks)
        identifiers = {}
        for block in blocks:
            identifiers[block] = block.collect(self)
        while blocks:
            current_block = blocks.pop(0)
            current_identifiers = identifiers[current_block]
            block_identifiers = list(current_identifiers)
            for block in blocks:
                block_identifiers += identifiers[block]
            nodelist = self.parser.parse(block_identifiers)
            token = self.parser.next_token()
            while token.contents not in current_identifiers:
                empty_block = blocks.pop(0)
                current_identifiers = identifiers[empty_block]
                self.blocks[empty_block.alias] = template.NodeList()
            self.blocks[current_block.alias] = nodelist
Пример #9
0
def content(parser, token):
    try:
        tag_name, base = token.split_contents()
    except ValueError:
        try:
            tag_name = token.split_contents()[0]
            base = None
        except:
            raise template.TemplateSyntaxError, "%r tag requires at least two arguments" % token.contents.split(
            )[0]

    nodelist = parser.parse(('end%s' % tag_name, ))

    if base:
        base = template.loader.get_template(base)

        basenodes = base.nodelist
        content = [
            i for i, n in enumerate(basenodes)
            if isinstance(n, template.loader_tags.BlockNode)
            and n.name == "content"
        ]
        if len(content):
            index = content[0]
            nodelist = template.NodeList(basenodes[0:index] + nodelist +
                                         basenodes[index:])

    parser.delete_first_token()
    return EmailPartNode(nodelist, tag_name)
Пример #10
0
 def __init__(self, parser, token):
     self._vars = {}
     tokens = list(utils.smarter_split(token.contents))[1:]
     self._process_positional_args(parser, tokens)
     self._process_named_args(parser, tokens)
     if self._meta.block:
         nodelists = {}
         block_names = [self._meta.end_block]
         other_blocks = isinstance(self._meta.block, dict) and \
                                             self._meta.block or {}
         block_names.extend(other_blocks)
         current = ''
         while True:
             attr = 'nodelist%s' % (current and '_%s' % current or '')
             nodelists[attr] = parser.parse(block_names)
             current = parser.next_token().contents
             parser.delete_first_token()
             if current == self.end_block:
                 break
         for name, required in other_blocks:
             if name in nodelists:
                 continue
             if required:
                 raise template.TemplateSyntaxError('Expected {%% %s %%}' %
                                                    name)
             nodelists[name] = template.NodeList()
         self.child_nodelists = list(nodelists)
         for attr, nodelist in nodelists:
             setattr(self, attr, nodelist)
Пример #11
0
def do_if_cached_page(parser, token):
    """
    It needed to have cmsutils.middleware.I18NFetchFromCacheMiddleware
    middleware in MIDDLEWARE_CLASSES settings

    Usage::

        {% if_cached_page %}
            do stuff
        {% else %}
            do stuff
        {% endif %}

    It need to have request in context (i.e. activate request context
    processor django.core.context_processors.request)
    """
    bits = token.contents.split()
    del bits[0]
    if bits:
        raise template.TemplateSyntaxError(
            "'if_cached_page' statement does not expect arguments")
    nodelist_true = parser.parse(('else', 'endif_cached_page'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endif_cached_page', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfCachedPageNode(nodelist_true, nodelist_false)
Пример #12
0
def do_if_was_rated(parser, token):
    """
    {% if_was_rated object %}...{% else %}...{% endif_was_rated %}
    """
    bits = token.contents.split()

    if len(bits) == 2:
        kwargs = {}
        # Opening tag
        obj = bits[1]
        if ":" in obj:
            ct, pk = obj.split(":")
            kwargs.update({"ct": int(ct), "pk": int(pk)})
        else:
            kwargs.update({"obj": obj})
        # Nodelist true
        nodelist_true = parser.parse(('else', 'endif_was_rated'))
        token = parser.next_token()
        kwargs.update({"nodelist_true": nodelist_true})
        # Nodelist false
        if token.contents == 'else':
            nodelist_false = parser.parse(('endif_was_rated', ))
            kwargs.update({"nodelist_false": nodelist_false})
            parser.delete_first_token()
        else:
            nodelist_false = template.NodeList()
        return IfWasRatedNode(**kwargs)

    raise template.TemplateSyntaxError, "{%% %s object %%}" % bits[0]
Пример #13
0
    def __init__(self, target=None, action=None, nodelist=None):
        self.target = target
        self.action = action or 'default'
        self.nodelist = nodelist or template.NodeList()

        self.parent = None
        if self.tag_name == 'forme' and self.target:
            # Rendering forme, load default style
            from forme import loader
            styles = loader.get_default_style()

            # Dj1.4, Dj1.5
            # Workaround for unsubscriptable SimpleLazyObject
            if hasattr(styles, '_wrapped'):
                bool(styles)
                self.styles = styles._wrapped
            else:
                self.styles = styles
        else:
            self.styles = Style()

        self.validate_child_nodes()
        self.update_styles()

        if self.tag_name == 'forme':
            if self.action == 'using':
                self.styles['forme'] = Style(template=self.nodelist)

            # Trigger nodes cleanup
            self.clean_nodelist()
Пример #14
0
 def parse_blocks(self):
     """
     Parse template blocks for block tags.
     
     Example:
         {% a %} b {% c %} d {% e %} f {% g %}
          => pre_c: b
             pre_e: d
             pre_g: f
         {% a %} b {% f %}
          => pre_c: b
             pre_e: None
             pre_g: None
     """
     if not self.options.blocks:
         return
     block_identifiers, block_aliases = [
         list(b) for b in zip(*self.options.blocks)
     ]
     while block_identifiers:
         nodelist = self.parser.parse(block_identifiers)
         token = self.parser.next_token()
         current_identifier = block_identifiers.pop(0)
         current_alias = block_aliases.pop(0)
         while token.contents != current_identifier:
             current_identifier = block_identifiers.pop(0)
             self.blocks[block_aliases.pop(0)] = template.NodeList()
         self.blocks[current_alias] = nodelist
     assert len(self.blocks) == len(
         self.options.blocks), "%s block parsing failed: %r => %r" % (
             self.tagname, self.options.blocks, self.blocks)
Пример #15
0
def do_is_author(parser, token):
    """The ``{% is_author %}`` tag displays the first section, if the user is
    the author of the recipe or a staff member. Otherwise the second section
    is displayed.

    ::

        {% is_author user recipe %}
            The user is owner of this recipe or a staff member.
        {% else %}
            The user has no right to edit this recipe.
        {% endis_author %}
    """
    try:
        tag_name, user, recipe = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            '%s requires a Recipe and an User as arguments' %
            token.contents.split()[0])
    nodelist_true = parser.parse(('else', 'endis_author'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endis_author', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IsAuthorNode(user, recipe, nodelist_true, nodelist_false)
Пример #16
0
def ifappexists(parser, token):
    """ Conditional Django template tag to check if one or more apps exist.

    Usage: {% ifappexists tag %} ... {% endifappexists %}, or
           {% ifappexists tag inventory %} ... {% else %} ... {% endifappexists %}

    """
    try:
        tokens = token.split_contents()
        apps = []
        apps += tokens[1:]
    except ValueError:
        raise template.TemplateSyntaxError(
            "Tag 'ifappexists' requires at least 1 argument.")

    nodelist_true = parser.parse(('else', 'endifappexists'))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_false = parser.parse(('endifappexists', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return AppCheckNode(apps, nodelist_true, nodelist_false)
Пример #17
0
def ifusergroup(parser, token):
    """ Check to see if the currently logged in user belongs to one or more groups
    Requires the Django authentication contrib app and middleware.

    Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or
           {% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %}

    """
    try:
        tokensp = token.split_contents()
        groups = []
        groups += tokensp[1:]
    except ValueError:
        raise template.TemplateSyntaxError(
            "Tag 'ifusergroup' requires at least 1 argument.")

    nodelist_true = parser.parse(('else', 'endifusergroup'))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_false = parser.parse(('endifusergroup', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return GroupCheckNode(groups, nodelist_true, nodelist_false)
Пример #18
0
def ifposition(parser, token):
    """
    Syntax::

        {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %}
        {% else %}
        {% endifposition %}

    """
    bits = list(token.split_contents())
    end_tag = 'end' + bits[0]

    nofallback = False
    if bits[-1] == 'nofallback':
        nofallback = True
        bits.pop()

    if len(bits) >= 4 and bits[-2] == 'for':
        category = template.Variable(bits.pop())
        pos_names = bits[1:-1]
    else:
        raise TemplateSyntaxError('Invalid syntax: {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %}')

    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 IfPositionNode(category, pos_names, nofallback, nodelist_true, nodelist_false)
Пример #19
0
def ifcansearch(parser, token):
    """
    Outputs the contents of the block if search is enabled.
    Search is considered to be enabled _unless_ Haystack has been
    configured to use the "disabled" backend.

    Examples::

        {% ifcansearch %}
            ...
        {% endifcansearch %}

        {% ifcansearch %}
            ...
        {% else %}
            ...
        {% endifcansearch %}
    """
    search_nodelist = parser.parse((
        'else',
        'endifcansearch',
    ))
    token = parser.next_token()
    if token.contents == 'else':
        nosearch_nodelist = parser.parse(('endifcansearch', ))
        parser.delete_first_token()
    else:
        nosearch_nodelist = template.NodeList()
    return IfCanSearchNode(search_nodelist, nosearch_nodelist)
Пример #20
0
def do_recurse(parser, token):
    nodelist = template.NodeList()
    templates_stack.append(nodelist)
    nodelist += parser.parse(('endrecurse', ))
    templates_stack.pop()
    node = RecurseNode(nodelist)
    parser.delete_first_token()
    return node
Пример #21
0
 def __init__(self, name, context, nodelist):
     self._name = name
     self._context = context
     self._nodelist = nodelist
     self._rendered_nodelist = template.NodeList()
     self['parentloop'] = context.get(name)
     context.push()
     context[name] = self
    def render(self, context):
        tabs = []
        tab_nodes = template.NodeList()
        other_nodes = template.NodeList()
        for node in self.node_list:
            if isinstance(node, PanelTabNode):
                tab_nodes.append(node)
                name = node.name.resolve(context)
                panel_id = 'mtp-tabpanel-%s' % name
                tabs.append({
                    'title':
                    node.title.resolve(context),
                    'attrs':
                    flatatt({
                        'id': 'mtp-tab-%s' % name,
                        'href': '#%s' % panel_id,
                        'role': 'tab',
                        'aria-controls': panel_id,
                        'aria-flowto': panel_id,
                    }),
                })
            else:
                other_nodes.append(node)

        tab_content = tab_nodes.render(context)
        other_content = other_nodes.render(context)
        cookie_name = self.cookie_name.resolve(
            context) if self.cookie_name else ''
        tab_label = self.tab_label.resolve(context) if self.tab_label else ''
        collapsable = self.collapsable.resolve(
            context) if self.collapsable else True
        css_class = self.css_class.resolve(context) if self.css_class else ''
        context.push()
        context['cookie_name'] = cookie_name
        context['css_class'] = css_class
        context['collapsable'] = collapsable
        context['tab_label'] = tab_label
        context['tabs'] = tabs
        context['tab_content'] = tab_content
        context['other_content'] = other_content
        tabbed_content = context.template.engine.get_template(
            self.template_name)
        rendered_html = tabbed_content.render(context)
        context.pop()
        return rendered_html
Пример #23
0
def ifnotsuit(parser, token):
    nodelist_true = parser.parse(('else', 'endifnotsuit'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifnotsuit',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfConditionNode(nodelist_true, nodelist_false, 'suit' not in settings.INSTALLED_APPS)
Пример #24
0
def ifnotdj110(parser, token):
    nodelist_true = parser.parse(('else', 'endifnotdj110'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifnotdj110',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfConditionNode(nodelist_true, nodelist_false, django.VERSION[:2] != (1, 10))
Пример #25
0
def ifhasfeed(parser, token):
    nodelist_true = parser.parse(('else', 'endifhasfeed'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifhasfeed', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfHasFeedNode(nodelist_true, nodelist_false)
Пример #26
0
def ifopenid(parser, token):
    nodelist_true = parser.parse(("else", "endifopenid"))
    token = parser.next_token()
    if token.contents == "else":
        nodelist_false = parser.parse(("endifopenid", ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfOpenidNode(nodelist_true, nodelist_false)
Пример #27
0
def ifinlineclasses(parser, token):
    nodelist_true = parser.parse(('else', 'endifinlineclasses'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifinlineclasses',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfConditionNode(nodelist_true, nodelist_false, hasattr(InlineModelAdmin, 'classes'))
Пример #28
0
def if_user_or_page_user(parser, token):
    nodelist_true = parser.parse(('else', 'endifuserorpageuser'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifuserorpageuser', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfUserOrPageUserNode(nodelist_true, nodelist_false)
Пример #29
0
 def handle_token(cls, parser, token, kind):
     nodelist_true = parser.parse(('else', 'end%s' % kind))
     token = parser.next_token()
     if token.contents == 'else':
         nodelist_false = parser.parse(('end%s' % kind, ))
         parser.delete_first_token()
     else:
         nodelist_false = template.NodeList()
     return cls(nodelist_true, nodelist_false, kind)
Пример #30
0
def ifisnotme(parser, token):
    nodelist_true = parser.parse(('else', 'endifisnotme'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifisnotme', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfIsNotMeNode(nodelist_true, nodelist_false)