Peer Pressure

Stuff to look at about looking at stuff. From Chris Dent. What?

Archive

Nov
24th
Tue
permalink

Templates For TiddlyWeb

There are a few ways to do server side template handling with TiddlyWeb. In one system TiddlyWiki style syntax is used to control output. That system is under development, based on the existing system TiddlyWebPages which uses Jinja2 templates that are stored in tiddlers in the TiddlyWeb store. Yet another system just uses Jinja2 directly. It’s that system which I’d like to write about today.

Jinja2 is a nicely straightforward pure Python templating system with optional C-based speedups and a syntax that is very similar to Django without requiring all the rest of Django. I like it because in addition to the standard render method on a template it also has generate which produces a generator. This can lead to some efficiencies with large pages.

Until recently using Jinja templates in TiddlyWeb was somewhat cumbersome: If you had multiple plugins each using templates, there was a fair amount of duplicated code. Now there is a new plugin tidldywebplugins.templates which abstracts that code away using just a single method for finding templates, and provides a system for packaging templates with plugins such that templates can be overridden in TiddlyWeb instances.

Use of tiddlywebplugins.templates is fairly straightforward, here’s an example:

The get_template in line 10 will first look in the directory specified by plugin_local_templates in tiddlywebconfig.py. This defaults to templates, relative to the instance, if not specified. If the template is not found then Jinja will use what is called a PackageLoader to look inside the tiddlywebplugins namespace package, in a templates directory for the template.

This allows templates to be overridden in an instance as required. It also means that plugins that are in the tiddlywebplugins namespace can put templates inside a tiddlywebplugins/templates directory in their own distribution.

The PackageLoader handling depends on a Python package being able inject content (the templates) into a package namespace that was created by a different package. This is tricky, and does not work with Python eggs. You can improve your chances of things working by doing installs with pip instead of easy_install.

get_template can be used anywhere in code that has a WSGI environ available to itself. That means it can be used in handlers (code which responds on a URL route), in serializers, in renderers, in WSGI middleware (such as HTMLPresenter). And if you don’t happen to have an environ handy you can just send an empty dictionary.

So there’s one way to handle templates in TiddlyWeb. In addition to being on PyPI, the code is also on github.

Comments (View)
blog comments powered by Disqus