我想使用列表的索引来获取列表的 values 。
我在views.py中有一个列表
视图.py
def home(request):
my_list=[("xy","abc","abcd"),("abcd","abc","xy")]
context={ "list"=my_list}
return render(request, 'index.html',context)
索引。html
{% for id in list%}
{% if id.1 =='abc' %}
{{id.0}}="Core user"
{{id.0}}
{% else %}
{{id.0}}
{% endif %}
{% endfor %}
因此,如果条件满足,列表的新 values 将是
[("xy","核心用户","abcd"),("abcd","核心用户","xy")]
我收到了语法错误。请让我知道我做错了什么以及如何解决这个问题?
回答1
元组数据类型不能修改。
因此,将元组数据类型转换为数组数据类型。
我推荐 https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#writing-custom-template-filters 和 https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#with with Shallow Copy
在views.py中
my_list=[["xy","abc","abcd"],["abcd","abc","xy"]]
在 custom.py 中
def set_core_user(my_list: list[str]) -> list[str]:
my_list[1] = "Core user"
return my_list
在 html
{% for id in list%}
{% if id.1 =='abc' %}
{{id.0}}="Core user"
{{id|set_core_user}}
{% else %}
{{id.0}}
{% endif %}
{% endfor %}