简体   繁体   中英

How to pass Django template variables to a WebPack module

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>   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM