Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 296
user1496984 Avatar asked May 28 '15 06:05

user1496984


1 Answers

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>   
like image 163
rrauenza Avatar answered Oct 04 '22 14:10

rrauenza