Passing django variables to javascript

久未见 提交于 2020-08-25 10:05:27

问题


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?


回答1:


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.




回答2:


<input type='hidden' value='{{ user.has_paid_plan}}' id='has_paid_plan' />


if ($('#has_paid_plan').val() == 'True') {
    isPayingUser = true;
} else {
    isPayingUser = false;
}



回答3:


Let's keep things simple. You don't have to use any other response type like JSON or anything else. The first thing that you do is pass the value from the backend. Assuming User model has a field as "has_paid_plan" as a BooleanField. If not please convert the same to a BooleanField.

views.py

context = dict()
context['user'] = user_instance
return render(request, 'template.html', context)

template.html

Add this to your script.

<script>
   .... // other code
    {% if user.has_paid_plan %}
        isPayingUser = true;
    {% else %}
        isPayingUser = false;
    {% endif %}
</script>

Try to keep things simple. It's a good practice. Hope this helps.



来源:https://stackoverflow.com/questions/52886765/passing-django-variables-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!