javascript - 将 Stringarray 交给 django 模板并在 d3 中使用它

标签 javascript python django d3.js

我想将 view.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 }};
...

在“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;]

最佳答案

您正在搜索的是“安全”过滤器:

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 中更频繁地使用变量,则将 off autoescape 转换为可能是有意义的。

关于javascript - 将 Stringarray 交给 django 模板并在 d3 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23635504/

相关文章:

django - 从超过 max_retries 失败的任务中恢复

javascript - 按列排序 div 并防止垂直自由空间

python - 基于 Django 类的 View 出现错误 : 'get_context_data() keywords must be strings'

python - 在 Python 3 中导入 Pyenchant 时出错

python - opencv simpleblobdetector - 获取已识别 blob 的 blob 属性

python - 如何在 apache 上配置 django 并在 apache 中创建 https 以便 django url 应使用 https ://<ip>:80 port 打开

javascript - 更新 Chrome 浏览器上的缓存文件

javascript - 如何通过嵌套 Gridview 中的按钮单击获取 TextBox 值

javascript - 地理包不渲染多边形来映射

django - 在保存过程中标记 django 模型实例以供以后处理