您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了如何使用JavaScript獲取Django模板指定鍵值數據,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
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.filter def getArgQxlValue(dictionary,arg): return dictionary[arg]['qxl'] @register.filter def getArgKkxValue(dictionary,arg): return dictionary[arg]['kkx'] @register.filter def 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}},就可以獲取到里面的值了
稍做美化
以上就是關于如何使用JavaScript獲取Django模板指定鍵值數據的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。