Context, context, who's got the context?

By Serdar Yegulalp | 2016/07/16 08:00


With template mappings, the one thing I've been struggling with is how to supply a context for the mappings. I've decided the smart thing to do is not to try and parse the Python expression used to create a template mapping, but instead to write mappings in an expression format that makes it possible to supply contexts manually.

Here's an example of what I mean. Let's say we want to do a simple year/month type of archive. For that we need two contexts: one that's based off the year component of the page's publication date, and the other its month. So we could create a mapping like this:

[
(
(page.year_context,page.month_context)
,'{}/{}/'+$i.format(page.date.year(),page.date.month())
)
]

The first item in the expression, the tuple, is a list of contexts to be applied, from left to right. The second item is the string expression that's generated from the page in context.

(The $i is a macro that expands to the index file name for the blog.)

For tags, things get a little more complicated. Since it's possible for more than one tag to be assigned to a page, we need to have a mapping like this:

[
(
(x.tag_context,)
,'tags/{}/'+$i.format(x)
) for x in page.tags_public
]

The context is derived from each tag, not the page as a whole, since we have to evaluate it for multiple tags in a page.

This looks a little complex at first glance, but I think it can be smoothed over by providing plenty of common examples.

A major advantage of this approach is it frees me from having to write some kind of parsing logic like I have now to determine what the context is for each template mapping. The context can be derived directly from a Python expression, which in turn points unambiguously to objects that return contexts.

Another really nice advantage of this approach is that it gives us a built-in way to allow templates to specify their own context handlers, by way of the mechanism I'm working out to allow code blocks in templates to function like plugins.

[Edit: This is something I plan to do eventually, probably not before 1.0 is out. Right now, the tokenization system we have now does work; it's just not where I want to stay forever.]


Tags: Python publishing templates


comments powered by Disqus