Reputation: 6211
As part of a Facebook sharekit, I have this code:
data-share-description="{% firstof foo.bar foo.baz bang.pow bang.zap %}"
which returns the correct value, but includes HTML tags. If I add a "striptags" filter after each value, it seems that firstof is recognizing "None" as a non-False value and returning that instead rather than proceeding down the list.
EDIT:
foo.bar = ''
foo.baz = None
bang.pow = '<i>Italicized text</i> and some more'
bang.zap = 'Something else'
Without striptags after each firstof variable, it returns <i>Italicized text</i> and some more
which is not what I want, but is what I expect. With strip tags, it prints out None
. If I remove foo.baz
from the firstof
sequence, I get the expected and desired value of Italicized text and some more
.
EDIT AGAIN:
Because foo.baz
is None
, striptags is throwing a TypeError of argument of type 'NoneType' is not iterable
. I think this is the problem but no idea how to fix it.
Upvotes: 1
Views: 447
Reputation: 18467
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.
Upvotes: 2