Below the Radar
Below the Radar

Reputation: 7635

Django pass var from view to two template in the same time

I would like to pass var from a view to the template and to a javascript library (javascript.js) in the same time. Is it possible?

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)

template:

{% 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 %}

Upvotes: 1

Views: 510

Answers (2)

Jack Shedd
Jack Shedd

Reputation: 3531

You don't need to "pass" the variable to the library.

Just set it in a script tag like so:

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

You can then reference it within your JS as either VARIABLE or window.foo.

Upvotes: 0

second
second

Reputation: 28637

assuming you want to keep your javascript files js only, one way to achieve this is to have your js initialize accept some config data. in your html template (which is rendered by django and thus has access to your context vars you pass data in

javascript.js

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

template.html

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

Upvotes: 2

Related Questions