Задать вопрос

Тел: +7 965 3737 888





Capture template output as a variable

<p>Tags like url and trans provide no way to get the result as a context variable. But how would you get a computed URL into a blocktrans?</p>
<p>This snippet solves the general problem. Just put the template code whose output you want to capture within captureas tags. For example:</p>
{% captureas login_url %}{% url login %}{% endcaptureas %}
{% blocktrans %}
&lt;a href="{{login_url}}"&gt;login&lt;/a&gt;

Вопрос полезен? Да0/Нет0

Ответы (3):

Ответ полезен? Да0/Нет0

The point, cubes, is actually to capture BLOCK output. Filters can indeed be wrapped with the filter block, but blocks can't take other blocks as arguments.

Good code for getting out of a quick bind. Could use improvement, but this completely fills the need. Hopefully this will get into the default tags by Django 1.3

Ответ полезен? Да0/Нет0

I found that the built in filter tag somewhat decreases my need for captureas, but it's still nifty. :)

Ответ полезен? Да0/Нет0

Thanks, I found this incredibly useful. One suggestion for improvement is to call django.utils.safestring.mark_safe on output after it is rendered in line 21.

This is because the render call performs HTML escaping of any interpolated variables, which means the newly created capture variable will be doubly escaped if it is not passed through the safe filter.