needs_autoescape in custom template filter vs model method

33 views
Skip to first unread message

fchow

unread,
Oct 21, 2013, 1:56:39 PM10/21/13
to django...@googlegroups.com
My question is about returning HTML markup in a model method vs. a custom template filter.

In the initial_letter_filter example given in https://docs.djangoproject.com/en/1.5/howto/custom-template-tags/
The function takes in autoescape as an arg, so it knows whether to apply conditional_escape or just lambda x: x  (pass-thru)

But if I write a model method that returns HTML markup, and I want to call this method in my template, does that method need to know the current auto-escaping state?  
The only example I see of returning HTML markup in a model method is the colored_name method: https://docs.djangoproject.com/en/1.5/ref/contrib/admin/
It calls format_html() which internally calls conditional_escape....so...it assumes autoescape state is on (unlike the template filter which takes autoescape as an arg)

Why does the custom filter need to know the autoescaping state but not the model  method?

Thanks.

Mike Dewhirst

unread,
Oct 21, 2013, 9:48:44 PM10/21/13
to django...@googlegroups.com
On 22/10/2013 4:56am, fchow wrote:
> My question is about returning HTML markup in a model method vs. a
> custom template filter.

Personally, I prefer the custom template filter due to a nicer
separation of model/display concerns.

That said, I recently discovered Django's mark_safe()

from django.utils.safestring import mark_safe

def known_good_html(value):
...
return mark_safe(value)

The returned object type is recognised by the template rendering engine
as not needing further escaping.

hth

Mike
Reply all
Reply to author
Forward
0 new messages