欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript获取Django模板中指定键值的数据,使用渲染器

程序员文章站 2022-06-13 19:06:32
Django中利用js来操作数据的常规操作一般为点(.)操作符来获取字典获列表的数据,一般入{{data.0}},{{data.arg}}等 但有时如果数据是嵌套类型的数据时,直接获取某个值就变得困难了,比如下面的格式要获取 这时候如果改变数据格式为列表中的无嵌套字典格式比较麻烦,可以自定义渲染器来 ......

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}}&nbsp;超出阀值&nbsp;&nbsp;阀值:{{guestsetargs|getargqxlvalue:j}}&nbsp;&nbsp;检测值:{{warningdata|getargqxlvalue:j}}<br>"
           document.write(setargstr);
       }
       
    {% endfor %} 
  {% endfor %} 
  
    </script>
</body>
</html>

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