<state data-value="{{ state }}"></state>
In my JavaScript file I have :
var state = document.getElementsByTagName('state')[0].getAttribute('data-value');
In the past this was done because of XHTML1.1 spec - what is the correct approach in today's times ?
<div data-value="{{ state }}"></div> ?
We could also do in the html template <script>var state = '{{ state }}';<script> but I have like a bunch of such assignments.
How else can we mass-assign JavaScript variables pushed in the HTML template ?
You could add something like this in the Django view context:
"MY_VARIABLES": json.dumps({
"state": "My state",
"number": 40,
"isActive": True,
...
})
And in the template assign only one variable and just use the values as object properties:
var MY_VARIABLES = {{ MY_VARIABLES|safe }};
> MY_VARIABLES.state
'My state'
> MY_VARIABLES.number
40
> MY_VARIABLES.isActive
true