手Stringarray django模板和使用它在d3

Hand Stringarray to django template and use it in d3

本文关键字:d3 Stringarray django      更新时间:2023-09-26

我想把一个字符串数组从我的views.py到模板,并使用这个字符串D3。

views.py:

def index(request):
    template = loader.get_template("myApp/index.html")
    data = ["a","b","c"]
    context = RequestContext(request,{"data":data})
    return HttpResponse(template.render(context))

index . html:

<html>
<head>
    <title>Some project</title>
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
    <h1>Some project visualisation</h1>
    <script type="text/javascript">
        var dataArray = {{ data }};
...

At "var dataArray = {{data}};"我得到一个语法错误。我在浏览器控制台和我的dataArray中查找了这个看起来像这样:

var dataArray = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]

我也尝试使用json.dumps(data),但我得到一个类似的dataArray,如:

var dataArray = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]

您要查找的是'safe'过滤器:

context = RequestContext(request,{"data":json.dumps(data)})

<script type="text/javascript">
    var dataArray = {{ data | safe }};

https://docs.djangoproject.com/en/dev/ref/templates/builtins/std: templatefilter-safe

如果你在javascript中更频繁地使用变量,那么关闭自动转义

可能是有意义的。