Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Assigning JavaScript variables to Django rendered variables in template files
<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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!