I’m pretty new to Django’s template system-
Basically, I’m trying to print out all the contents of a list that I’m passing to django in a context.
The relevant part of my urls.py is here-
url(r'^class/$', twobooks.classes.views.getAllInformation, {'template_name':'classes/displayBooks.html'}),
Now, in my views getAllInformation is as follows-
def getAllInformation(searchTerm,template_name):
nameAndNumberStore = modifySearchTerm(searchTerm)
url = modifyUrl(nameAndNumberStore)
soup = getHtml(url)
information = []
if (checkIfValidClass(soup,nameAndNumberStore)):
storeOfEditions = getEdition(soup)
storeOfAuthorNames = getAuthorName(soup)
storeOfBookNames = getBookNames(soup)
storeOfImages = getImages(soup)
information.append(storeOfAuthorNames)#REMEMBER this is a list of two lists
information.append(storeOfEditions)
return render_to_response(
template_name,
{'authors': storeOfAuthorNames},
)
and displayBooks.html is as follows-
<html>
<head>
<body>
<h1>Testing the class page backend</h1>
<ul>
{ % for author in authors|safe% }
<li>{{ author }}</li>
{ % endfor % }
</ul>
</body>
</html>
I think this is fairly simple, but I’m not sure what’s going on, so thought I’d ask for some help – thanks!
Applying the
safefilter 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 literalu"[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 aSafeStringinstance not aunicodeinstance). Then, iteration is going over each character in the produced string, which isn’t what you want.Instead, you can use the
safeseqfilter which applies thesafefilter to each element in the sequence,Or, you could apply
safeto the value inside the iterator.I would recommend
safeseq, as you may then be able to optimise the template further, if you wish, with theunordered_listfilter, 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.)