How to filter a template tag?

I have a tag that looks like this:

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

It just creates an empty form. But now I want to pass the result of this to the escapejs filter escapejs that I can use it in a JavaScript variable. How can i do this?

+8
django django-templates
source share
3 answers

Many tags support as variablename — that is, just put as variablename at the end of the tag, and then the output of that tag is placed in the variable, not displayed.

This tag {% partial %} can support this. Here is an example if it does:

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

If the tag in question is a fragment of the "Partial tag" , then it seems that it does not support this. But perhaps it could be rewritten to support it.

You can use snippet

 {% captureas myvar %}{% partial "partials/vehicleform.html" vehicle=vehicles.empty_form %}{% endcaptureas %}{{ myvar|escapejs }} 
+15
source share

Another solution for getting data into a JS variable:

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

Then fill it and remove at the same time

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

The advantage of this solution is that your other JS scripts can pre-process it before you rip it out of the DOM. escapejs also creates large files with all of these escape characters.

+1
source share

Applying a filter to the output of a template tag can also be performed without any external dependencies using the built-in filter template tag. From the documentation :

[This tag template] filters the contents of a block through one or more filters. Using channels, you can specify multiple filters, and filters can have arguments, as in the syntax of variables.

An example in the original question will be written like this:

 {% filter escapejs %} {% partial "partials/vehicleform.html" vehicle=vehicles.empty_form %} {% endfilter %} 
0
source share

All Articles