Do something useful
You can skip this part if you don't feel like doing something useful right now. :-)
Now that we have our view in place, we can start actually doing something with it. Like listing all keywords of the items that the folder contains, and letting the user do a search based on those.
For that, we'll add a couple of methods to our existing view in browser.py for our template to use.
listAllTags returns a list of keywords in the order of their popularity. This is the implementation:
class MyView(BrowserView):
def listAllTags(self):
weighted_tags = dict()
for item in self.query():
for keyword in item.Subject:
if keyword in weighted_tags:
weighted_tags[keyword] = weighted_tags[keyword] + 1
else:
weighted_tags[keyword] = 1
items = sorted(weighted_tags.items(), lambda a,b:cmp(b[1], a[1]))
return [i[0] for i in items]
def query(self, **kw):
path = '/'.join(self.context.getPhysicalPath())
return self.context.portal_catalog(path=path, **kw)
Then we'll create two other methods for our template: tagSelected will tell us whether a tag has been selected already, and addTagToURL will add a tag to the query parameters. The implementation of these methods goes like this:
from urllib import quote_plus
# ...
def tagSelected(self, tag):
return tag in self.getTags()
def addTagToURL(self, tag):
base = self.request.URL + '?'
query = ''
for existing_tag in self.getTags():
query += 'tags:list=%s&' % quote_plus(existing_tag)
query += 'tags:list=' + quote_plus(tag)
return base + query
def getTags(self):
return self.request.form.get('tags', [])
This is how we present the list of tags in the template:
<h2>Tags</h2>
<ul>
<li tal:repeat="tag view/listAllTags">
<a href="#"
tal:omit-tag="python:view.tagSelected(tag)"
tal:attributes="href python:view.addTagToURL(tag)"
tal:content="tag"
/>
</li>
</ul>
However, this is hardly useful without any results. Again, the real work is done in the view:
def searchResults(self):
return self.query(Subject=dict(query=self.getTags(), operator='and'))
and the template just calls searchResults:
<h2>Results</h2>
<ul>
<li tal:repeat="item view/searchResults">
<a href="#"
tal:attributes="href item/getURL;
title item/Description"
tal:content="item/Title"
/>
</li>
</ul>
