将django变量传递给javascript [英] Passing django variables to javascript

查看:88
本文介绍了将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.

这篇关于将django变量传递给javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆