[Answered ]-Use firstof and striptags

2👍

Since striptags seems to choke on None values, you could chain another call to default. That means you’d end up with something like this:

{% firstof foo.baz|default:''|striptags bar.quux|default:''|striptags %}

for each element in the list. I believe you’ll agree this is quite cumbersome.

This is why I think it’s time for you to create your own custom tag that performs this procedure for you:

from django import template
from django.utils.html import strip_tags

register = template.Library()

@register.simple_tag
def firstof_striptags(*args):
    for arg in args:
        if arg:
            return strip_tags(arg)

I’m not sure this fully complies with your use case and you may want to read up on some topics like Auto-escaping Considerations. This code is untested but should give you an idea what to do.

Leave a comment