3

I want to pass the argument to the javascript via the django view.

I always separate the js code and html code into two files, index.html and index.js.

Here is the django view

def index(request):
    template = loader.get_template('index.html')
    context = RequestContext(request,{'name':'guest'})
    return HttpResponse(template.render(context))

I have the index.html like this

Access the argument name in index.html is ok.

<!DOCTYPE html>
<meta charset="utf-8">
{% load staticfiles %}
<script> 
var name='{{ name }}'
console.log(name) //guest
</script> 
<script src="{% static "js/index.js" %}"></script>
</body>

But in the external index.js, I can not access the argument.

var name ='{{ name }}'
console.log(name) //'{{name}}'

How can I pass the argument or variable to the external javascript?

Thank you!

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
alec.tu
  • 1,647
  • 2
  • 20
  • 41
  • you cannot! You could call the function that you need from the html file and this way you can pass the parameter or you should put the value in an hidden element in the DOM and then read it from the external js file – Francesco Mar 26 '15 at 15:35
  • There are many solutions here: https://stackoverflow.com/questions/298772/django-template-variables-and-javascript – CarloDiPalma Feb 07 '23 at 19:51

1 Answers1

0

You've already made the name variable available globally in the script block in index.html. You can just refer to it directly from any other piece of JS as name.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895