سؤال

I want to hand over a stringarray from my views.py to the template and use this strings for 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 }};" I get a syntax error. I looked this up in the browser-console and my dataArray seems to look like this:

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

I have also tried to use json.dumps(data), but I get a similar dataArray like:

var dataArray = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]
هل كانت مفيدة؟

المحلول

What you are searching for is the 'safe' filter:

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

If you use variables more often in your javascript, it would probably make sense to turn off autoescape

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top