Project

General

Profile

TemplateParser » History » Version 4

« Previous - Version 4/56 (diff) - Next » - Current version
Elmer de Looff, 2012-02-09 16:34


TemplateParser

The µWeb TemplateParser is a in-house developed templating engine that provides tag replacement, tag-functions and template control functions. This document will describe the following:

First though, to help with understanding the TemplateParser, a minimal size template document:

Hello [title] [name]

The above document contains two simple template tags. These tags are delimited by square brackets, and they will be replaced by the named argument provided during parsing. If this name is not present, then the literal presentation of the tag will remain in the output.

Template class

The Template class provides the interface for pre-parsing templates, loading them from files and parsing single templates to completion. During pre-parsing, constructs such as loops and conditional statements are converted to TemplateLoop and TemplateConditional objects, and their scopes nested appropriately in the Template. Tags are replaced by TemplateTag instances, and text is captured in TemplateText. All of these provide Parse methods, which together result in the combined parsed template output.

Creating a template

A template is created simple by providing a string input to the Template's constructor. This will return a valid Template instance (or raise an error if there is a problem with the syntax:

import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])

Above can be seen the various parts of the template, which will be combined to output once parsed.

Loading a template from file

The Template class provides a classmethod called FromFile, which loads the template at the path.

Loading a template named example.utp from the current working directory:

import templateparser
>>> template = templateparser.Template.FromFile('example.utp')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])

Parsing a template

Parsing a template can be done by calling the Template's Parse method. The keyword arguments provided to this call will from the replacement mapping for the template. In the following example, we will provide one such keyword, and leave the other undefined to show the (basic) behavior of the Template.Parse method.

import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template.Parse(title='senor')
'Hello senor [name]'

Parser class

Using TemplateParser inside µWeb

Templating language syntax