From 8e51feddbab51d157a4a9405988834818b24c3bf Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Wed, 21 Jul 2010 12:19:50 -0400 Subject: [PATCH] Add ability to filter recipe lists by tag --- cookbook/cookbook.py | 36 ++++++++++++++++++++++++++++++++++ cookbook/server.py | 9 ++++++--- cookbook/template/recipes.html | 10 +++++++++- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/cookbook/cookbook.py b/cookbook/cookbook.py index b3e3ed0..2c395c5 100644 --- a/cookbook/cookbook.py +++ b/cookbook/cookbook.py @@ -384,6 +384,14 @@ class Recipe (object): Mix ingredients until salamander starts to smoke Serve warm over rice + >>> r.matches_tags(None) + True + >>> r.matches_tags([]) + True + >>> r.matches_tags(['dinner', 'apprentice']) + True + >>> r.matches_tags(['dinner', 'dragon']) + False >>> pprint.pprint(r.to_yaml()) {'author': 'Merlin', 'directions': 'Mix ingredients until salamander starts to smoke\\n\\nServe warm over rice', @@ -439,6 +447,18 @@ class Recipe (object): name = name.replace(from_, to) return name + def matches_tags(self, tags): + """Return True if this recipe is tagges with each of the tags in tags. + """ + if tags in [None, []]: + return True + if self.tags == None: + return False + for t in tags: + if t not in self.tags: + return False + return True + def __str__(self): return str(self.__unicode__()) @@ -521,6 +541,22 @@ class Cookbook (list): self.index[recipe.name] = recipe self.index[recipe.clean_name()] = recipe + def tags(self): + """List all tags used in this cookbook. + """ + tags = set() + for recipe in self: + if recipe.tags != None: + tags = tags.union(set(recipe.tags)) + return sorted(tags) + + def tagged(self, tags=None): + """Iterate through all recipes matching the given list of tags. + """ + for recipe in self: + if recipe.matches_tags(tags): + yield recipe + def test(): import doctest diff --git a/cookbook/server.py b/cookbook/server.py index 49ddb9e..81f8208 100644 --- a/cookbook/server.py +++ b/cookbook/server.py @@ -40,14 +40,17 @@ class Server (object): pass @cherrypy.expose - def index(self, status='open', assignee='all', target='all'): + def index(self, tag=None): """Recipe index page. - Recipes can be filtered or sorted using a variety of criteria. + Recipes can be filtered by tag. """ + if isinstance(tag, types.StringTypes): + tag = [tag] template = self.env.get_template('recipes.html') return template.render(cookbook=self.cookbook, - recipes=list(self.cookbook)) + recipes=list(self.cookbook.tagged(tag)), + selected_tags=tag) @cherrypy.expose def recipe(self, name=None): diff --git a/cookbook/template/recipes.html b/cookbook/template/recipes.html index 02ecddb..52e2fed 100644 --- a/cookbook/template/recipes.html +++ b/cookbook/template/recipes.html @@ -1,10 +1,18 @@ {% extends "base.html" %} {% block page_title %} - Index + Index {% if selected_tags %}({{ ', '.join(selected_tags) }}){% endif %} {% endblock %} {% block content %} +
+ + +