【问题标题】:How can I use a variable to lookup in a tuple? (Django)如何使用变量在元组中查找? (姜戈)
【发布时间】:2016-06-25 19:38:04
【问题描述】:

我有一个元组,这样

{{VISIBILITY_CHOICES.1.1}}

输出“你好”。

我有一个带有属性“visibility_status”的模型“task”,并且在一个循环中,说 task.visibility_status 的所有迭代输出 1

{{task.visibility_status}}

输出 1。

如何在元组的查找中使用这个 task.visibility_status?类似 VISIBILITY_CHOICES[task.visibility_status][1] 的其他语言。

我对 django 很陌生...非常感谢。

编辑: 我运行的代码:

{% for task in tasks %}
    <div class="post">
         <h1><a href="">{{ task.subject }}</a></h1>
         <div class="date">
             <p>Due: {{ task.due_date }}</p>
             <p>Assigned to: {{task.assigned_to}}</p>
         </div>
         <p>{{ task.text_area|linebreaks }}</p>
         {% with args=""|add:task.visibility_status|add:",1" %}
         <p>Visibility Status: {{VISIBILITY_CHOICES|get_index:args}}({{ task.visibility_status }})</p>
         {% endwith %}
         <p>Case Status: {{ task.case_status }}</p>
         <div class="date">
             <p>Created: {{ task.created_date }} by {{ task.author }}</p>
         </div>
     </div>
{% endfor %}

【问题讨论】:

标签: django django-templates


【解决方案1】:

虽然内置名称tuple 在模板中可能没有任何语法意义,但我将在下面的代码中使用my_tuple 代替它。

我使用with 创建了一个上下文,该上下文构建了用于索引my_tuple(即task.visibility_status 和1)的参数::

{% with x=task.visibility_status|stringformat:"s" %}
{% with args=x|add:",1" %}

    {{ my_tuple|get_index:args }}

{% endwith %}
{% endwith %}

在custom template filter 中,我已经拆分并重新创建了参数,并在普通 python 中使用索引来返回索引处的项目:

from django import template

register = template.Library()

@register.filter
def get_index(my_tuple, args):
    arg1, arg2 = args.split(',') # split on the comma separator
    try:
        i = int(arg1)
        j = int(arg2)
        return my_tuple[i][j] # same as my_tuple[task.status][1]
    except: 
        return None

【讨论】:

  • add:task.status 有问题;该变量未传递到模板过滤器中。当我输出“args”时,它只显示“,1” {{task.status}} 仍然在模板中正确输出。
  • 我想要的是 {% with args=""|add:{{task.status}}|add:",1" %} 但这是无效的代码,当然。
  • {{task.status}} 显示什么?您不需要在 {%%} 中使用 {{}}
  • 它显示整数 1、2 或 3,具体取决于它所在的循环实例。
  • 您是在with 外部还是内部运行循环?愿你能用你模板的那部分更新你的帖子。
猜你喜欢
  • 2011-01-27
  • 2015-07-18
  • 2017-05-05
  • 2021-07-02
  • 2020-08-17
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
相关资源
最近更新 更多