Django同时将var从视图传递到两个模板

时间:2013-02-23 15:36:03

标签: javascript django django-templates django-views

我想将var从视图传递到模板并同时传递到javascript库(javascript.js)。有可能吗?

view.py:

def setAppOptions(request, map_name):
    if request.user.is_authenticated():
        app_selected = EzApp.objects.get(app_name=app_name, created_by=request.user)
        formset = ezAppOptionFormSet(user=request.user, instance=app_selected)
        if request.method == 'POST':
            formset = ezAppOptionFormSet(request.POST, instance=app_selected, user=request.user)
            if formset.is_valid():
                formset.save()

        return render_to_response("manage_app_options.html", {'formset': formset}, context_instance=RequestContext(request)) 
    else:
        error_msg = u"You are not logged in"
        return HttpResponseServerError(error_msg)

模板:

{% extends "basemap.html" %}
{% block library %}
#I want to pass var to this library and to this template in the same time...
<script type="text/javascript" src="/static/javascript.js"></script>
{% endblock %}
{% block content %}
<table border="1">
<tr>
<td>
    <h1>Define App options</h1>
    {% if formset.errors %}
        <p style="color: red;">
            Please correct the error{{ formset.errors|pluralize }} below.
        </p>
    {% endif %}
    <form method="post" action="" encrypt="multipart/form-data">{% csrf_token %}
            {{ formset.as_p }} 
        <input type="submit" value="Submit" onclick="initialize()">
    </form>
</td>
</tr>
</table>
{% endblock %}

2 个答案:

答案 0 :(得分:2)

假设您只想保留javascript文件js,实现此目的的一种方法是让您的js initialize接受一些配置数据。在您的html模板中(由django呈现,因此可以访问您的上下文变量,您可以在

中传递数据)

javascript.js

...
function initialize(options) {
...

template.html

<input type="submit" value="Submit" onclick="initialize({
    myvar: {{ value_from_django }},
    other_stuff: 10
})">

答案 1 :(得分:0)

您无需将变量“传递”到库中。

只需将其设置在脚本标记中,如下所示:

{% block library %}
<script type="text/javascript">
    var foo = "{{ variable }}";
</script>
<script type="text/javascript" src="/static/javascript.js"></script>
{% endblock %}

然后,您可以在JS中将其引用为VARIABLEwindow.foo