【问题标题】:django template tags, work with an array outputdjango 模板标签,使用数组输出
【发布时间】:2014-07-17 03:23:46
【问题描述】:

我创建了一个输出为数组的标签:

from django import template
register = template.Library()

def create_array(context):
    output=[1,2,3,4]
return output

register.simple_tag(takes_context=True)(create_array)

当我在模板中调用这个标签时:{% load create_array %} {% create_array %},打印了数组,但是我无法通过这种方式访问​​每个元素:

{% load create_array %}
{% for i in create_array %} {{i}} {% forend %}

知道如何访问每个元素吗?

错误是在模板渲染期间:异常值:'create_array' object is not iterable。

PS:我需要标签中的“上下文”,所以我只是写了一个简短的例子。我正在使用 Django 版本 1.6.2

【问题讨论】:

    标签: arrays django tags django-templates


    【解决方案1】:

    @laffuste 有一个要点,您需要使用as 命令将数组存储到模板变量中,然后再遍历它。然而,有一种更简洁的方式来编写标签——事实上,这正是 Assignment Tags 的用途:

    from django import template
    register = template.Library()
    
    @register.assignment_tag(takes_context=True)
    def create_array(context):
        return [1,2,3,4]
    

    就是这样——赋值标签完成了令人讨厌的解析工作并返回一个模板变量友好的输出。 laffuste 对模板的回答中的所有内容正是您所需要的,但只是为了让您可以将它们全部放在一个地方,这里再次复制它,所以它们都在一个地方:

    {{ load my_custom_tags }}
    
    {% create_array as my_array %}
    
    {% for item in my_array %}
         {{ item }}
    {% endfor %}
    
    【解决方案2】:

    要获取forloop 中每个对象的索引,请使用forloop.counter,如下所示:

    {% load create_array %}
    {% for i in create_array %} 
         {{ forloop.counter }}
    {% forend %}
    

    如果你想在 forloop 中达到某个计数时执行某项操作,请使用以下代码:

    {% for i in create_array %}
        {% if forloop.counter == 1 %}
           Do something with {{ i }}.
        {% endif %}
    {% endfor %}
    

    这是 forloop 计数器的 Django 文档:

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

    【讨论】:

    • 我仍然有一个错误,消息是:“'create_array' object is not iterable”。此错误发生在模板渲染期间。
    【解决方案3】:

    恐怕没有比……更简单的方法了

    from django import template
    from django.template.base import TemplateSyntaxError
    
    register = template.Library()
    
    @register.tag(name='create_array')
    def create_array(parser, token):
    
        class ArrayCreator(template.Node):
            def __init__(self, var_name):
                self.var_name = var_name # output variable
    
            def render(self, context):
                context[self.var_name] = [1, 2, 3, 4] # access to context
                return ''
    
        args = token.contents.split() # "create_array", "as", VAR_NAME
    
        if len(args) != 3 or args[1] != 'as':
            raise TemplateSyntaxError("'create_array' requires 'as variable' (got %r)" % args)
    
        return ArrayCreator(args[2])
    

    在模板中的使用:

    {{ load my_custom_tags }}
    
    {% create_array as my_array %}
    
    {% for item in my_array %}
        {{ item }}
    {% endfor %}
    

    但也许有人会带来更轻更好的东西?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 2011-09-30
      • 2014-03-20
      • 2011-06-15
      • 2017-01-09
      • 2019-08-06
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多