[Django]-Django display contents of list in a template

4đź‘Ť

âś…

Applying the safe filter will turn anything into a string. If you start with the literal [1, 2, 'foo', u'bar'], you’re going to end up with approximately the literal u"[1, 2, 'foo', u'bar']" (or something like it—I’m not quite certain of how it’s rendered as I’ve never tried doing it; also I say “approximately” as it’s actually a SafeString instance not a unicode instance). Then, iteration is going over each character in the produced string, which isn’t what you want.

Instead, you can use the safeseq filter which applies the safe filter to each element in the sequence,

<ul>
{% for author in authors|safeseq %}
    <li>{{ author }}</li>
{% endfor %}
</ul>

Or, you could apply safe to the value inside the iterator.

<ul>
{% for author in authors %}
    <li>{{ author|safe }}</li>
{% endfor %}
</ul>

I would recommend safeseq, as you may then be able to optimise the template further, if you wish, with the unordered_list filter, if you only wish to display the values. (Note that I’m not certain of how it behaves—it’s possible that this would unmark it as safe. You’d need to try it.)

<ul>{{ authors|safeseq|unordered_list }}</ul>
👤Chris Morgan

2đź‘Ť

It would help if you mentioned the data format for storeOfAuthorNames, the output you’re currently getting, and what you’re expecting instead.

All I can tell from your view is:

  • authors (storeOfAuthorNames) is produced by getAuthorName(soup)
  • if checkIfValidClass(...) returns False, you’ll end up with a NameError when trying to reference storeOfAuthorNames since it will be undeclared

If I had to guess where your problem is based solely on your example template, I’d say your problem is with authors|safe. You’ll want to apply the safe filter on the value you’re printing out, not the list itself. i.e.

<ul>
{ % for author in authors %}
    <li>{{ author|safe }}</li>
{ % endfor % }
</ul>
👤Shawn Chin

Leave a comment