예제 #1
0
    def render(self, context):
        if 'forloop' in context:
            parentloop = context['forloop']
        else:
            parentloop = {}
        context.push()
        try:
            values = self.sequence.resolve(context, True)
        except VariableDoesNotExist:
            values = []
        if values is None:
            values = []
        if not hasattr(values, '__len__'):
            values = list(values)
        len_values = len(values)
        if len_values < 1:
            context.pop()
            return self.nodelist_empty.render(context)
        nodelist = NodeList()
        if self.is_reversed:
            values = reversed(values)
        unpack = len(self.loopvars) > 1
        # Create a forloop value in the context.  We'll update counters on each
        # iteration just below.
        loop_dict = context['forloop'] = {'parentloop': parentloop}
        for i, item in enumerate(values):
            # Shortcuts for current loop iteration number.
            loop_dict['counter0'] = i
            loop_dict['counter'] = i + 1
            # Reverse counter iteration numbers.
            loop_dict['revcounter'] = len_values - i
            loop_dict['revcounter0'] = len_values - i - 1
            # Boolean values designating first and last times through loop.
            loop_dict['first'] = (i == 0)
            loop_dict['last'] = (i == len_values - 1)

            pop_context = False
            if unpack:
                # If there are multiple loop variables, unpack the item into
                # them.
                try:
                    unpacked_vars = dict(zip(self.loopvars, item))
                except TypeError:
                    pass
                else:
                    pop_context = True
                    context.update(unpacked_vars)
            else:
                context[self.loopvars[0]] = item
            for node in self.nodelist_loop:
                nodelist.append(node.render(context))
            if pop_context:
                # The loop variables were pushed on to the context so pop them
                # off again. This is necessary because the tag lets the length
                # of loopvars differ to the length of each set of items and we
                # don't want to leave any vars from the previous loop on the
                # context.
                context.pop()
        context.pop()
        return nodelist.render(context)
예제 #2
0
   def render(self, context):
      permissions = [permission.resolve(context, True) for permission in self.permissions]

      #
      #  check if has permissions
      #
      from core.helper import get_request
      from core.permission import check_permissions
      status, action = check_permissions(get_request(), permissions)

      nodelist = NodeList()
      if status:
         for node in self.nodelist_permission:
            try:
               nodelist.append(node.render(context))
            except Exception as e:
               if not hasattr(e, 'django_template_source'):
                  e.django_template_source = node.source
               raise
      else:
         if self.nodelist_nopermission:
            for node in self.nodelist_nopermission:
               try:
                  nodelist.append(node.render(context))
               except Exception as e:
                  if not hasattr(e, 'django_template_source'):
                     e.django_template_source = node.source
                  raise

      return nodelist.render(context)
예제 #3
0
def remove_block_nodes(nodelist, block_stack, block_context):
    new_nodelist = NodeList()
    for node in nodelist:
        if isinstance(node, VariableNode):
            var_name = node.filter_expression.token.strip()
            if var_name == 'block.super':
                if not block_stack:
                    continue
                node = block_context.get_block(block_stack[-1].name)
                if not node:
                    continue
        if isinstance(node, BlockNode):
            expanded_block = expand_blocknode(node, block_stack, block_context)
            new_nodelist.extend(expanded_block)
        else:
            # IfNode has nodelist as a @property so we can not modify it
            if isinstance(node, IfNode):
                node = copy(node)
                for i, (condition,
                        sub_nodelist) in enumerate(node.conditions_nodelists):
                    sub_nodelist = remove_block_nodes(sub_nodelist,
                                                      block_stack,
                                                      block_context)
                    node.conditions_nodelists[i] = (condition, sub_nodelist)
            else:
                for attr in node.child_nodelists:
                    sub_nodelist = getattr(node, attr, None)
                    if sub_nodelist:
                        sub_nodelist = remove_block_nodes(
                            sub_nodelist, block_stack, block_context)
                        node = copy(node)
                        setattr(node, attr, sub_nodelist)
            new_nodelist.append(node)
    return new_nodelist
예제 #4
0
    def render(self, context):
        if 'forloop' in context:
            parentloop = context['forloop']
        else:
            parentloop = {}
        context.push()
        try:
            values = self.sequence.resolve(context, True)
        except VariableDoesNotExist:
            values = []
        if values is None:
            values = []
        if not hasattr(values, '__len__'):
            values = list(values)
        len_values = len(values)
        if len_values < 1:
            context.pop()
            return self.nodelist_empty.render(context)
        nodelist = NodeList()
        if self.is_reversed:
            values = reversed(values)
        unpack = len(self.loopvars) > 1
        # Create a forloop value in the context.  We'll update counters on each
        # iteration just below.
        loop_dict = context['forloop'] = {'parentloop': parentloop}
        for i, item in enumerate(values):
            # Shortcuts for current loop iteration number.
            loop_dict['counter0'] = i
            loop_dict['counter'] = i+1
            # Reverse counter iteration numbers.
            loop_dict['revcounter'] = len_values - i
            loop_dict['revcounter0'] = len_values - i - 1
            # Boolean values designating first and last times through loop.
            loop_dict['first'] = (i == 0)
            loop_dict['last'] = (i == len_values - 1)

            pop_context = False
            if unpack:
                # If there are multiple loop variables, unpack the item into
                # them.
                try:
                    unpacked_vars = dict(zip(self.loopvars, item))
                except TypeError:
                    pass
                else:
                    pop_context = True
                    context.update(unpacked_vars)
            else:
                context[self.loopvars[0]] = item
            for node in self.nodelist_loop:
                nodelist.append(node.render(context))
            if pop_context:
                # The loop variables were pushed on to the context so pop them
                # off again. This is necessary because the tag lets the length
                # of loopvars differ to the length of each set of items and we
                # don't want to leave any vars from the previous loop on the
                # context.
                context.pop()
        context.pop()
        return nodelist.render(context)
def remove_block_nodes(nodelist, block_stack, block_context):
    new_nodelist = NodeList()
    for node in nodelist:
        if isinstance(node, VariableNode):
            var_name = node.filter_expression.token.strip()
            if var_name == 'block.super':
                if not block_stack:
                    continue
                node = block_context.get_block(block_stack[-1].name)
                if not node:
                    continue
        if isinstance(node, BlockNode):
            expanded_block = expand_blocknode(node, block_stack, block_context)
            new_nodelist.extend(expanded_block)
        else:
            # IfNode has nodelist as a @property so we can not modify it
            if isinstance(node, IfNode):
                node = copy(node)
                for i, (condition, sub_nodelist) in enumerate(node.conditions_nodelists):
                    sub_nodelist = remove_block_nodes(sub_nodelist, block_stack, block_context)
                    node.conditions_nodelists[i] = (condition, sub_nodelist)
            else:
                for attr in node.child_nodelists:
                    sub_nodelist = getattr(node, attr, None)
                    if sub_nodelist:
                        sub_nodelist = remove_block_nodes(sub_nodelist, block_stack, block_context)
                        node = copy(node)
                        setattr(node, attr, sub_nodelist)
            new_nodelist.append(node)
    return new_nodelist
예제 #6
0
def do_random(parser, token):
    """
    Output the contents of a random block.

    The `random` block tag must contain one or more `or` tags, which separate
    possible choices; a choice in this context is everything between a
    `random` and `or` tag, between two `or` tags, or between an `or` and an
    `endrandom` tag.

    Sample usage::

        {% random %}
            You will see me half the time.
        {% or %}
            You will see <em>me</em> the other half.
        {% endrandom %}
    """
    options = NodeList()

    while True:
        option = parser.parse(('or', 'endrandom'))
        token = parser.next_token()
        options.append(option)
        if token.contents == 'or':
            continue
        parser.delete_first_token()
        break
    if len(options) < 2:
        raise TemplateSyntaxError
    return RandomNode(options)
예제 #7
0
def angularjs(parser, token):
    """
    Conditionally switch between AngularJS and Django variable expansion.

    Usage::

        {% angularjs 1 %} or simply {% angularjs %}
            {% process variables through the AngularJS template engine %}
        {% endangularjs %}

        {% angularjs 0 %}
            {% process variables through the Django template engine %}
        {% endangularjs %}

        Instead of 0 and 1, it is possible to use a context variable.
    """
    bits = token.contents.split()
    if len(bits) < 2:
        bits.append('1')
    values = [parser.compile_filter(bit) for bit in bits[1:]]
    django_nodelist = parser.parse(('endangularjs',))
    angular_nodelist = NodeList()
    for node in django_nodelist:
        # convert all occurrences of VariableNode into a TextNode using the
        # AngularJS double curly bracket notation
        if isinstance(node, VariableNode):
            node = TextNode('{{ %s }}' % node.filter_expression.token)
        angular_nodelist.append(node)
    parser.delete_first_token()
    return AngularJsNode(django_nodelist, angular_nodelist, values[0])
예제 #8
0
def do_random(parser, token):
    """
    Output the contents of a random block.

    The `random` block tag must contain one or more `or` tags, which separate
    possible choices; a choice in this context is everything between a
    `random` and `or` tag, between two `or` tags, or between an `or` and an
    `endrandom` tag.

    Sample usage::

        {% random %}
            You will see me half the time.
        {% or %}
            You will see <em>me</em> the other half.
        {% endrandom %}
    """
    options = NodeList()

    while True:
        option = parser.parse(('or', 'endrandom'))
        token = parser.next_token()
        options.append(option)
        if token.contents == 'or':
            continue
        parser.delete_first_token()
        break
    if len(options) < 2:
        raise TemplateSyntaxError
    return RandomNode(options)
예제 #9
0
def angularjs(parser, token):
    """
    Conditionally switch between AngularJS and Django variable expansion.

    Usage::

        {% angularjs 1 %} or simply {% angularjs %}
            {% process variables through the AngularJS template engine %}
        {% endangularjs %}

        {% angularjs 0 %}
            {% process variables through the Django template engine %}
        {% endangularjs %}

        Instead of 0 and 1, it is possible to use a context variable.
    """
    bits = token.contents.split()
    if len(bits) < 2:
        bits.append('1')
    values = [parser.compile_filter(bit) for bit in bits[1:]]
    django_nodelist = parser.parse(('endangularjs', ))
    angular_nodelist = NodeList()
    for node in django_nodelist:
        # convert all occurrences of VariableNode into a TextNode using the
        # AngularJS double curly bracket notation
        if isinstance(node, VariableNode):
            node = TextNode('{{ %s }}' % node.filter_expression.token)
        angular_nodelist.append(node)
    parser.delete_first_token()
    return AngularJsNode(django_nodelist, angular_nodelist, values[0])
예제 #10
0
    def slots_in_template(self, template):
        nodelist = NodeList()
        for node in template.template.nodelist:
            if (node.token.token_type == TokenType.BLOCK
                    and node.token.split_contents()[0] == "slot"):
                nodelist.append(node)

        return nodelist
예제 #11
0
 def render(self, context):
     context.push();
     kwargs = self.resolve_kwargs(context)
     items = Item.objects(type=kwargs['type']).order_by('-itemMeta.versionCreated')[:kwargs['length']]
     nodelist = NodeList()
     for item in items:
         context['item'] = item
         for node in self.nodelist:
             nodelist.append(node.render(context))
     context.pop()
     return nodelist.render(context)
예제 #12
0
 def render(self, context):
     context.push()
     items = self.get_items(context)
     nodelist = NodeList()
     context['package'] = context['item']
     first = True
     for item in items:
         context['item'] = item
         context['first'] = first
         for node in self.nodelist:
             nodelist.append(node.render(context))
         first = False
     context.pop()
     return nodelist.render(context)
예제 #13
0
 def render(self, context):
     context.push()
     nodelist = NodeList()
     kwargs = self.resolve_kwargs(context)
     limit = kwargs.get('limit', 55)
     start = kwargs.get('start', 0)
     order = kwargs.get('order', '-versionCreated')
     items = Item.objects(itemClass=kwargs['class'],publishedOn__ne=None).order_by(order)[start:limit]
     for item in items:
         context['item'] = item
         for node in self.nodelist:
             nodelist.append(node.render(context))
     context.pop()
     return nodelist.render(context)
예제 #14
0
   def render(self, context):
      from core.helper import get_request
      request = get_request()
      context['request'] = request
      context['wepo'] = request.wepo

      nodelist = NodeList()

      for node in self.nodelist_field:
         try:
            nodelist.append(node.render(context))
         except Exception as e:
            if not hasattr(e, 'django_template_source'):
               e.django_template_source = node.source
            raise

      return nodelist.render(context)
예제 #15
0
   def render(self, context):
      section = self.section.resolve(context, True)
      page = self.page.resolve(context, True)

      import json
      page_blocks = page.blocks if page and page.blocks else []
      page_section = page_blocks[section] if section in page_blocks else []

      nodelist = NodeList()

      context[self.output_var] = page_section

      for node in self.nodelist_field:
         try:
            nodelist.append(node.render(context))
         except Exception as e:
            if not hasattr(e, 'django_template_source'):
               e.django_template_source = node.source
            raise

      return nodelist.render(context)
예제 #16
0
    def render(self, slots_filled=None, *args, **kwargs):
        slots_filled = slots_filled or []
        context_args_variables = getfullargspec(self.context).args[1:]
        context_args = {
            key: kwargs[key]
            for key in context_args_variables if key in kwargs
        }
        context = self.context(**context_args)
        template = get_template(self.template(context))
        slots_in_template = self.slots_in_template(template)

        if slots_in_template:
            valid_slot_names = set([slot.name for slot in slots_in_template])
            nodelist = NodeList()
            for node in template.template.nodelist:
                if (node.token.token_type == TokenType.BLOCK
                        and node.token.split_contents()[0] == "slot"):
                    if node.name in valid_slot_names and node.name in slots_filled:
                        nodelist.append(TextNode(slots_filled[node.name]))
                    else:
                        for node in node.nodelist:
                            nodelist.append(node)
                else:
                    nodelist.append(node)

            render_context = Context(context)
            with render_context.bind_template(template.template):
                return nodelist.render(render_context)

        return template.render(context)
예제 #17
0
    def render(self, context):
        if "forloop" in context:
            parentloop = context["forloop"]
        else:
            parentloop = {}
        context.push()
        try:
            values = self.sequence.resolve(context, True)
        except VariableDoesNotExist:
            values = []
        if values is None:
            values = []
        if not hasattr(values, "__len__"):
            values = list(values)
        len_values = len(values)
        if len_values < 1:
            context.pop()
            return self.nodelist_empty.render(context)
        nodelist = NodeList()
        if self.is_reversed:
            values = reversed(values)
        unpack = len(self.loopvars) > 1
        # Create a forloop value in the context.  We'll update counters on each
        # iteration just below.
        loop_dict = context["forloop"] = {"parentloop": parentloop}
        for i, item in enumerate(values):
            # Shortcuts for current loop iteration number.
            loop_dict["counter0"] = i
            loop_dict["counter"] = i + 1
            # Reverse counter iteration numbers.
            loop_dict["revcounter"] = len_values - i
            loop_dict["revcounter0"] = len_values - i - 1
            # Boolean values designating first and last times through loop.
            loop_dict["first"] = i == 0
            loop_dict["last"] = i == len_values - 1

            pop_context = False
            if unpack:
                # If there are multiple loop variables, unpack the item into
                # them.
                try:
                    unpacked_vars = dict(zip(self.loopvars, item))
                except TypeError:
                    pass
                else:
                    pop_context = True
                    context.update(unpacked_vars)
            else:
                context[self.loopvars[0]] = item
            # In TEMPLATE_DEBUG mode provide source of the node which
            # actually raised the exception
            if settings.TEMPLATE_DEBUG:
                for node in self.nodelist_loop:
                    try:
                        nodelist.append(node.render(context))
                    except Exception as e:
                        if not hasattr(e, "django_template_source"):
                            e.django_template_source = node.source
                        raise
            else:
                for node in self.nodelist_loop:
                    nodelist.append(node.render(context))
            if pop_context:
                # The loop variables were pushed on to the context so pop them
                # off again. This is necessary because the tag lets the length
                # of loopvars differ to the length of each set of items and we
                # don't want to leave any vars from the previous loop on the
                # context.
                context.pop()
        context.pop()
        return nodelist.render(context)