Note that there are some explanatory texts on larger screens.

plurals
  1. POPython ~ accessing tuple members in template class
    text
    copied!<p>I am new to Python - be forewarned!</p> <p>I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class:</p> <pre><code>class ListTemplate: def __init__(self, input_list=[]): self.input_list = input_list def __str__(self): return "\n".join([self._template % x for x in self.input_list]) </code></pre> <p>Here's the template code/class:</p> <pre><code>class HTML_Template(ListTemplate): _template = """ &lt;li&gt; &lt;table width="100%%" border="0"&gt; &lt;tr&gt; &lt;td&gt;Title: %(title)s&lt;/td&gt; &lt;td&gt;Link: %(isbn)s&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Author: %(author)s&lt;/td&gt; &lt;td&gt;Date: %(pub_date)s&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Summary: %(isbn)s&lt;/td&gt; &lt;td&gt;Description: %(descr)s&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;hr&gt; &lt;/li&gt;""" </code></pre> <p>Here's the problem:</p> <p>I'm pulling data from a sqlite database using fetchall, which return a list of tuples. I can pass this list of tuples to this method fine by changing the template to %s instead of %(isbn) ...etc., however, I need to access the isbn member multiple times in the template. To do this now, I load the tuples in to dictionaries and push them into another list ...then pass the list of dictionaries. This strikes me as inefficient. My question is: how would you rewrite this so that the original list of tuples could be passed to the template (thus, saving a step ), while still allowing access to the individual members by ie., item[0] or similar?</p> <p>Thanks ~</p> <p>Bubnoff </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload