views.py
def somefunction(request):
var = True
return render(request, dasboard.html)
myfirst.js
function myFunction() {
}
How I get var from views.py into the myfirst.js function?
CodePudding user response:
It isn't possible to give a 100% correct answer without knowing the templating engine you are using (DTL, Jinja2?). However, if var
doesn't contain any sensitive/private data, the general solution is to pass var
to your html template through the context
parameter of the render
function:
# views.py
views.py
def somefunction(request):
var = True
context = { "var": var }
return render(request, dasboard.html, context)
Then, expose var
as a data-*
attribute on a html element in your template (the exact implementation will change based on the templating engine you are using):
<!-- dashboard.html -->
<div id="info" data-var="{{ var }}" >
...
</div>
Finally, in your javascript file, you simply retrieve the same html element and access var
through the special dataset
property:
// myfirst.js
function myFunction() {
var infoElement = document.getElementById("info");
var varValue = infoElement.dataset.var;
}