简体   繁体   English

如何在 django html 模板中使用 javascript 字符串作为变量名?

[英]How to use javascript string as variable name in django html template?

I have a django view that passes a multiple of values to my html page.我有一个 django 视图,它将多个值传递给我的 html 页面。 Based on some client side process, I want to process one of those values.基于某些客户端流程,我想处理这些值之一。 Consider the example:考虑这个例子:

views.py视图.py

return render(request,'output.html',{
    'k1'=x,
    'k2'=y,
    'k3'=z,
}

output.html:输出.html:

<script>
    var temp;
    var i;
for (i=1;i<=3;i++){
        temp="k"+i.toString();
    }

Now I want to access value in variable whose name is stored in temp to perform some jquery operations.现在我想访问名称存储在 temp 中的变量中的值来执行一些 jquery 操作。 So I need the value stored in a javascript variable.所以我需要存储在 javascript 变量中的值。

Note: the given is just a small example, I am actually using a loop of about 60 iterations, ie k1 to k60, So hard Coding if else is not a feasible option.注意:给出的只是一个小例子,我实际上使用了一个大约 60 次迭代的循环,即 k1 到 k60,所以如果 else 不是一个可行的选择,那么硬编码。

Use JSON for data you want to use in your HTML template.对要在 HTML 模板中使用的数据使用 JSON。 Then you can work with it as it would be JS.然后你可以像使用 JS 一样使用它。

<script>var data = {{ data | jsonify }}; </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM