I'm writing a Django app and while somewhat familiar with Django I'm pretty unfamiliar with JavaScript. I'm adding a few lines of JavaScript into one of my pages in order to include a map.
The script simply encompasses initializing the map and then adding markers according to information saved in my database.
Given that there is so little code, would it still be considered bad practice to leave the script in the HTML template and pass information from my database using {{info}}
?
If so, what method would you consider to be better?
I assume what you're suggesting is putting both the JS script and its required data into the template (the data being injected into the JS script through string interpolation)
You can see how this can get quickly out of hand. Below I provide levels of code organization, in approximate ascending order (the further you go to better, in general)
First: putting the JS into its own .js file and including it via <script>
tag is easy. So let's do that. Moreover, modern browsers can load files in parallel, so it's a plus to load the HTML and JS files simultaneously.
Now the other problem I've seen people do is pass the data into the JS using a <script>data = {"info": "something"}</script>
before including their JS code.
Which isn't ideal either for many reasons, stemming from the fact that the data is being string-interpolated in the Django template:
However since you said you are familiar with Django, I'd like to suggest you create a view that returns the data that your client side JS needs in JSON format. E.g. something that returns {"info": "something"}
on /api/info
.
There's lots of ways to achieve this, here's a start (albeit might be outdated)
Then I'd have the script.js file read the data with a simple HTTP GET call. Lots of JS libraries can do this for you easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With