No activity today, make something!
tweb-filters Filter Plugin Tutorial

20161127110230 cdent  

To put filter plugins in practical terms we'll build one that makes it possible to select and sort tiddlers based on the number of tags the tiddlers have. For example select=tags:4 would get those tiddlers that have four tags. select=tags:>3 would get those that have more than three tags. And sort=-tags would return the tiddlers ordered by number of tags. Note that "tags" is already an attribute on tiddlers, but since it is a list is not already used in selections.

Prior to following the tutorial please review select, sort, the code referenced in Filter Plugins and the background in Extending Filters.

The final code for this can be found on github.

Step One: Initialize a Plugin

Every plugin has an init function which boots up the plugin at TiddlyWeb startup time. For filters nothing need to happen in init, but it still needs to be there:

def init():

Once a plugin is a plugin, in order for the code to be used in an instance, it must be added to the

config = {
    system_plugins: ['tagscount'],

Step Two: Sort Tags

In order to sort tags we have to count tags. First we add a tag_count methods to ATTRIBUTE_SORT_KEY:

def tag_count(attribute):
    Return the length of the tags or
    the value of the sort we are doing.
        return int(attribute)
    except TypeError:
        return len(attribute)

ATTRIBUTE_SORT_KEY['tags'] = tag_count

Because both the value from the entity and, when selecting, the value being compared against are passed to this method, we have to handle both a string to integer conversion as well as delivering the length of tiddler.tags.

Step Three: Select by Tags Count

We need to add the "tags" attribute to ATTRIBUTE_SELECTOR and a by_tag_count method to handle selecting:

def by_tag_count(entity, attribute, value):
    Return true if the number of tags is value.
    return tag_count(entity.tags) == int(value)

ATTRIBUTE_SELECTOR['tags'] = by_tag_count

by_tag_count returns True if the number of tags on the entity is equal to the value provided in the selector.


That's it. Please look at the full code sample to see included tests and how everything hangs together.