简体   繁体   中英

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. Based on some client side process, I want to process one of those values. Consider the example:

views.py

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

output.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. So I need the value stored in a javascript variable.

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.

Use JSON for data you want to use in your HTML template. Then you can work with it as it would be JS.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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