Django Template Variables and Javascript

后端 未结 15 2350
误落风尘
误落风尘 2020-11-22 05:59

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}

相关标签:
15条回答
  • 2020-11-22 06:08

    you can assemble the entire script where your array variable is declared in a string, as follows,

    views.py

        aaa = [41, 56, 25, 48, 72, 34, 12]
        prueba = "<script>var data2 =["
        for a in aaa:
            aa = str(a)
            prueba = prueba + "'" + aa + "',"
        prueba = prueba + "];</script>"
    

    that will generate a string as follows

    prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"
    

    after having this string, you must send it to the template

    views.py

    return render(request, 'example.html', {"prueba": prueba})
    

    in the template you receive it and interpret it in a literary way as htm code, just before the javascript code where you need it, for example

    template

    {{ prueba|safe  }}
    

    and below that is the rest of your code, keep in mind that the variable to use in the example is data2

    <script>
     console.log(data2);
    </script>
    

    that way you will keep the type of data, which in this case is an arrangement

    0 讨论(0)
  • 2020-11-22 06:14

    I've been struggling with this too. On the surface it seems that the above solutions should work. However, the django architecture requires that each html file has its own rendered variables (that is, {{contact}} is rendered to contact.html, while {{posts}} goes to e.g. index.html and so on). On the other hand, <script> tags appear after the {%endblock%} in base.html from which contact.html and index.html inherit. This basically means that any solution including

    <script type="text/javascript">
        var myVar = "{{ myVar }}"
    </script>
    

    is bound to fail, because the variable and the script cannot co-exist in the same file.

    The simple solution I eventually came up with, and worked for me, was to simply wrap the variable with a tag with id and later refer to it in the js file, like so:

    // index.html
    <div id="myvar">{{ myVar }}</div>
    

    and then:

    // somecode.js
    var someVar = document.getElementById("myvar").innerHTML;
    

    and just include <script src="static/js/somecode.js"></script> in base.html as usual. Of course this is only about getting the content. Regarding security, just follow the other answers.

    0 讨论(0)
  • 2020-11-22 06:18

    CAUTION Check ticket #17419 for discussion on adding similar tag into Django core and possible XSS vulnerabilities introduced by using this template tag with user generated data. Comment from amacneil discusses most of the concerns raised in the ticket.


    I think the most flexible and handy way of doing this is to define a template filter for variables you want to use in JS code. This allows you to ensure, that your data is properly escaped and you can use it with complex data structures, such as dict and list. That's why I write this answer despite there is an accepted answer with a lot of upvotes.

    Here is an example of template filter:

    // myapp/templatetags/js.py
    
    from django.utils.safestring import mark_safe
    from django.template import Library
    
    import json
    
    
    register = Library()
    
    
    @register.filter(is_safe=True)
    def js(obj):
        return mark_safe(json.dumps(obj))
    

    This template filters converts variable to JSON string. You can use it like so:

    // myapp/templates/example.html
    
    {% load js %}
    
    <script type="text/javascript">
        var someVar = {{ some_var | js }};
    </script>
    
    0 讨论(0)
  • 2020-11-22 06:18

    Here is what I'm doing very easily: I modified my base.html file for my template and put that at the bottom:

    {% if DJdata %}
        <script type="text/javascript">
            (function () {window.DJdata = {{DJdata|safe}};})();
        </script>
    {% endif %}
    

    then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)

    Hope it helps!

    0 讨论(0)
  • 2020-11-22 06:19

    The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.

    Having said that, you can put this kind of substitution into your JavaScript.

    <script type="text/javascript"> 
       var a = "{{someDjangoVariable}}";
    </script>
    

    This gives you "dynamic" javascript.

    0 讨论(0)
  • 2020-11-22 06:19

    Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.

    <script type="text/javascript">
        var myVar = "{{ myVar }}"
    </script>
    
    <script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>
    

    data is defined in the view as usual in the get_context_data

    def get_context_data(self, *args, **kwargs):
        context['myVar'] = True
        return context
    
    0 讨论(0)
提交回复
热议问题