且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Django 模板中使用变量索引访问列表?

更新时间:2023-01-09 08:06:08

是的,您无法解析变量名称.绝对非常努力地将这个逻辑放在视图中.

Right, you can't resolve variable names. Definitely try very hard to put this logic in the view.

但在 5% 的情况下,我确实发现这种限制有时需要太多 的视图/模板作者控制之外所需的更改逻辑.我开始接受一些个人定制,允许在视图中进行变量分配以及简单的变量分辨率.

But 5% of the time, I do find this extremely limiting at times requiring too much logic in the view / changes required outside the template authors control. I've come to accept a few personal customizations, allowing for variable assignment within the view as well as simple variable resolution.

使用模板引擎所有查找在一个"系统(索引、属性、键),构建一个这样做的模板标签非常简单.

It's quite simple to build a template tag that does so though, using the template engines "all lookups in one" system (index, attribute, key).

from django.template import Variable, VariableDoesNotExist

@register.assignment_tag()
def resolve(lookup, target):
    try:
        return Variable(lookup).resolve(target)
    except VariableDoesNotExist:
        return None

{% resolve some_list some_index as value %}
{% resolve some_dict some_dict_key as value %}