Django Template Variables and Javascript

后端 未结 15 2379
误落风尘
误落风尘 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: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 %}
    
    
    

提交回复
热议问题