How do Django template variables pass to external js calls

  • 2020-06-12 09:52:21
  • OfStack

preface

Due to the need of work, I have been thinking about how to better organize static resources in Django, such as JS and CSS1 classes. How to combine the front-end build tools to write better code and structure? The following article will give you a detailed introduction to the implementation of the method, without saying much, let's start with a detailed introduction:

The methods are as follows:

The first problem that needs to be solved is that at some point the JS code needs to be written in the template to get the variables passed in the background, such as:


<div>
<h1>Test</h1>
<div id="my-test" ></div>
</div>
<script>
$(function(){
 $('#my-test').html("{{ some_var_from_view }}")
});
</script>

If you write this code in this way, it's hard to say that the front-end build tools like webpack will be much less widely used.

To begin with, I can't think of a good way to completely strip out JS and templates without having to render data using templates. If the reader has a good way to ask for advice.
Since you can't do it all, do your best to separate the data and code needed for JS.

Since you need the template to render the data for JS, the first idea is to render the data into HTML code and hide it. The advantage of this approach is that it is so simple that it can be eliminated from the template altogether < script > < /script > The label. The downside is that a lot of hidden fields are rendered, and a lot of getElementsByxxxx1 class code is written in JS to get the data.

In this case, use one compromise, in HTML < script > < /script > The tag renders the data passed in the background as an JS object, which can then be used directly in the JS code.

For example, in the template:


<script>
var MyViewVar = {
 var_1: {{ var_1 }},
 var_2: {{ var_2 }},
};
</script>
...
<script type="text/javascript" src="/js/test_script.js"></script>

One thing to note when using this approach is to try to write the code that renders the JS variable, such as in head, before introducing the external JS file. This makes it possible to use the object MyViewVar directly in ES56en_script.js.

Of course, since SPA (Single Page Application) is popular now, django only provides JSON data as the back end is another way, but this is a test of the ability of the front end.

conclusion


Related articles: