I am just learning about WebPack module, and I am thinking of moving the entire JS infrastructure of my Django app to modules. It seems that a straightforward way of doing this is to create a webpack module for each Django template (or view), and have a single <script>
tag on each page.
However, I'm trying to find a way of passing the content of Django template variables to these webpack modules. Previously I could have these variables inlined:
<script>
//Sample code..
var arr = [];
{% for s in vars %}
arr.push(s);
{% endfor %}
</script>
Now, I only have:
<script src="temp.js"></script>
One potential solution I found is to define the webpack module to be a library that exports a single root function to the global namespace in the browser. Then use an inline script
tag to put the Django variables into a JS variable, and pass this as arguments to the exported function.
This somehow feels like a clumsy way of doing things. Any ideas as to how I can handle this better?
Thanks!
Here is how I've done it, based on dpwrussel's hint in the question's comments and this question:
In my module that I'm importing, I do this:
var React = require('react')
var ReactDOM = require('react-dom')
window.render_my_thing = function(properties) {
ReactDOM.render(...)
}
Then in my django template, I add the following:
<script>
render_my_thing({
property1: "{{ property1 }}",
property2: "{{ property2 }}",
})
</script>
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