【问题标题】:Using complex variables in django templates在 django 模板中使用复杂变量
【发布时间】:2011-02-23 12:54:03
【问题描述】:

在下面的模板中,user.group 是一个数字,它必须显示为 group_name.get(user.group) 是否可以传递给模板 group_name dict 并在模板中使用 group_name.get(user.group)

<table>
{% for user in users %}
<tr>    
    <td>{{ user.name }}</td>
    <td>{{ user.age }}</td>
    <td>{{ user.group}}</td>
</tr> 
{% endfor %}
</table>

【问题讨论】:

    标签: django templates dictionary


    【解决方案1】:

    本着 django 的精神,这个逻辑应该存在于代码中,而不是模板中。你不能添加一个返回组的方法user.get_group()吗?

    【讨论】:

      【解决方案2】:

      不,点表示法不允许通过变量值查找名称。

      如果特定于这个模板,我会在视图中执行此操作。

      for user in users:
          users.group_name = group_name.get(user.group)
      
      
      {% for user in users %}
          {{ user.group_name }}
      {% endfor %}
      

      如果它适用于所有用户,请按照 jammon 的建议进行并在User上定义一个方法

      出于好奇,我可以看看你的模型吗?只是好奇为什么 group 是一个数字以及group_name 的来源。

      【讨论】:

        猜你喜欢
        • 2020-04-30
        • 1970-01-01
        • 2014-07-15
        • 2014-07-23
        • 2016-02-02
        • 1970-01-01
        • 2011-03-04
        • 2021-06-02
        相关资源
        最近更新 更多