How can I pass my context variables to a javascript file in Django?

前端 未结 3 1935
庸人自扰
庸人自扰 2020-12-02 14:50

This question must be obvious but I can\'t figure it out.

In a template, I link to a js file in my media directory. From that file, I would like to access a context

相关标签:
3条回答
  • 2020-12-02 15:01

    In addition to Andrzej Bobak's answer, you can also generate a global variable in Javascript from your template. For example, your template might generate code like this:

    <script>
       var my_chart = {{ the_chart }};
    </script>
    

    Your script could then refer to my_chart.

    0 讨论(0)
  • 2020-12-02 15:01

    I would also add because I ran into the error a few times that if the python variable is an object it will throw a syntax error unless you put it in quotes, in other words, within your template,

    <script>
       var my_var = '{{ python_object|escapejs }}';
    </script>
    

    Furthermore, before putting that object in the context it is best to first serialize it to JSON, or you'll end up having to do string parsing. I found also that date objects needed to be converted to strings before this step.

    import jsonpickle
    
    context['python_object'] = jsonpickle.encode(python_object)
    

    And finally, in the JS you can then iterate through the object properly and use the values as you probably would have in python by doing:

    var my_var_parsed = jQuery.parseJSON(my_var);
    
    0 讨论(0)
  • 2020-12-02 15:03

    I don't think it's possible this way. If you want to access some data provided by the view, you have to pass it to the js function.

    Example

    js file:

    my_cool_js_function(some_param){
        // do some cool stuff
    }
    

    view

    // some html code
    
    my_cool_js_function({{param}})
    

    hope this helps :)

    0 讨论(0)
提交回复
热议问题