I'm having a difficult time passing variables from the python backend to javascript. A lot of my variables look like this in javascript:
if ('{{ user.has_paid_plan}}' == 'True') {
isPayingUser = true;
} else {
isPayingUser = false;
}
It's ugly and I'm sure there's a much cleaner way to do this. How should this be done?
This may be an odd approach, but I suppose one way to solve this would be to pass a json object as a variable, which would contain all other variables. For example:
def user(request):
user = request.user
ctx = {
'isPayingUser': user.is_paying_user()
'age': user.age
'username': user.email
}
json_ctx = json.dumps(ctx)
ctx['json_ctx'] = json_ctx
return render(request, 'template.html', ctx)
In this way you have access to all the django/python variables, and you also have all the variables properly json-encoded as the "json_ctx" object which you can use in your javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With