I've got a tag that looks like this:
{% partial "partials/vehicleform.html" vehicle=v开发者_如何学Cehicles.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?
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 }}
Applying a filter to the output of a template tag can also be accomplished without any external dependencies using the built in filter
template tag. From the documentation:
[This template tag] filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax.
The example in the original question would be written like this:
{% filter escapejs %}
{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form %}
{% endfilter %}
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.
精彩评论