我在我的python模板上有这个for循环来实现值数组:
labels: [{% for bftimes in dataBF.buffers.0.times %} "{{ bftimes }}", {% endfor %}]
我想知道是否可以将int变量用作索引,而不是直接编写它,如上面的代码所示。
我需要使用下拉列表的所选值的索引:
//returns the index of the selected value
document.getElementById("buffer").selectedIndex
最佳答案
这个问题需要更多背景信息,以帮助我们了解您的目标。看来您正在将python与javascript数据结构混合在一起。
我的一般建议是,首先准备python数据结构使其符合需要,然后将其转换为json。 Django模板语言中的循环仅应在简单情况下使用。
如果使用django> = 2.1,则可以使用json-script
模板标记
{{ data|json_script:"my-data" }}
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#json-script
如果没有,您可以使用
# views.py
import json
def foo(request):
dataBF = {"a": [{"c": [1,2,3,1,1]},{"d": [1,2,3,1,1]}]}
# here you can manipulate the data accordingly to what you need
data = json.dumps(dataBF)
return render(request, "index.html", context={"data": data})
在模板方面
<script>
const datajs = {{ data | safe }};
</script>
datajs是可以使用的javascript对象。
我举了一个例子,您可以检查https://repl.it/@IvanPereira/python-to-javascript-django-template
关于python - 我可以在Python的for循环中使用变量作为索引吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55093190/