将django变量传递给javascript
我在将变量从python后端传递到javascript时遇到了困难。我的很多变量在javascript中看起来像这样:
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?
这可能是一个奇怪的方法,但是我想解决这个问题的一种方法是通过一个json对象作为变量,其中将包含所有其他变量。例如:
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)
通过这种方式,您可以访问所有django / python变量,并且还可以对所有变量进行json编码为 json_ctx
对象,可以在javascript中使用。
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.