使用JavaScript获取Django模板指定键值数据

时间:2021-05-25

Django中利用js来操作数据的常规操作一般为点(.)操作符来获取字典或列表的数据,一般如{{data.0}},{{data.arg}}

但有时如果数据是嵌套类型的数据时,直接获取某个值就变得困难了,比如下面的格式要获取

correct中qxl的值

startArgsSet={"correct":{"qxl":0,"kkx":0},"reliable":{"qxl":0,"kkx":0},"security":{"qxl":0,"kkx":0},"understand":{"qxl":0,"kkx":0},"entropy":{"qxl":0,"kkx":0},"mature":{"qxl":0,"kkx":0},"active":{"qxl":0,"kkx":0},"service":{"qxl":0,"kkx":0},"file":{"qxl":0,"kkx":0},"tech":{"qxl":0,"kkx":0},"property":{"qxl":0,"kkx":0},"organize":{"qxl":0,"kkx":0},"develop":{"qxl":0,"kkx":0},"source":{"qxl":0,"kkx":0},"update":{"qxl":0,"kkx":0},"fix":{"qxl":0,"kkx":0},"quality":{"qxl":0,"kkx":0},"meanNum":{"qxl":0,"kkx":0},"variance":{"qxl":0,"kkx":0}}

这时候如果改变数据格式为列表中的无嵌套字典格式比较麻烦,可以自定义过滤器来获取数据,

from django.template.defaulttags import register@register.filterdef getArgQxlValue(dictionary,arg): return dictionary[arg]['qxl'] @register.filterdef getArgKkxValue(dictionary,arg): return dictionary[arg]['kkx'] @register.filterdef getArgName(dictionary,arg): return dictionary[arg]['name']

在模板中就可以以这样写

<!-- the second important page of the project-->{% load staticfiles %}<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>超标信息</title> <script src="{% static 'js/a-mynewjs.js' %}"></script></head><body> {{ guestSetArgs|safe }}<br><br><br> {{ warningdata|safe }}<br><br> <script> {% for i in guestSetArgs %} {% for j in warningdata %} if("{{i}}"=="{{j}}") { if(Number({{warningdata|getArgQxlValue:j}})>Number({{guestSetArgs|getArgQxlValue:i}})) var setArgStr="{{warningdata|getArgName:i}}超出阀值阀值:{{guestSetArgs|getArgQxlValue:j}}检测值:{{warningdata|getArgQxlValue:j}}<br>" document.write(setArgStr); } {% endfor %} {% endfor %} </script></body></html>

形如{{warningdata|getArgQxlValue:j}},就可以获取到里面的值了

稍做美化

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章