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?
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
The <template> tag is used as a container to hold some HTML content hidden from the user when the page loads. The content inside <template> can be rendered later with a JavaScript. You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it.
You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.
Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With