views:

32

answers:

2

I've got a tag that looks like this:

{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form %}

Which just renders an empty form. But now I want to pass the output of that to the escapejs filter so that I can use it in a JavaScript variable. How can I do that?

+1  A: 

Many tags support as variablename -- that is, simple put as variablename at the end of the tag and then the output of that tag is placed in the variable rather than displayed.

This {% partial %} tag may support that. Here's an example, if it does:

{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form as myvar %}{{ myvar|escapejs }}

If the tag in question is the "Partial tag" snippet then it appears it doesn't support this. But it probably could be rewritten to support it.

You could use the "Capture template output as a variable" snippet, and then apply the filter to the captured content, like so:

{% captureas myvar %}{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form  %}{% endcaptureas %}{{ myvar|escapejs }}
Jordan Reiter
It's a modified version of the partial tag snippet that supports variable naming. http://djangosnippets.org/snippets/2104/ I think the `captureas` sol'n should work.
Mark
A: 

Another solution to get the data into a JS variable:

<div class="display:none" id="empty-vehicle-form">{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form %}</div>

Then nab it and remove it at the same time

var empty_form = $('#empty-vehicle-form').remove().html();

The advantage of this solution is that your other JS scripts can preprocess it before you rip it out of the DOM. escapejs also creates bigger filesizes with all those escape chars.

Mark