TemplateParser » History » Version 6
Version 5 (Elmer de Looff, 2012-02-09 16:36) → Version 6/56 (Elmer de Looff, 2012-02-09 17:08)
h1. 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:
* The [[TemplateParser#template|Template class]], used to parse the templating language
* The [[TemplateParser#parser|Parser class]], which provides template loading and caching
* [[TemplateParser#using|Using TemplateParser]] inside a µWeb PageMaker
* A detailed explanation of the [[TemplateParser#syntax|templating language syntax]], constructs and behaviors
First though, to help with understanding the TemplateParser, a minimal size template document:
<pre><code class="html">
Hello [title] [name]
</code></pre>
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.
h1(#template). 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.
h2. 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 [[TemplateParser#syntax|syntax]]:
<pre><code class="python">
import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])
</code></pre>
Above can be seen the various parts of the template, which will be combined to output once parsed.
h2. 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:
<pre><code class="python">
import templateparser
>>> template = templateparser.Template.FromFile('example.utp')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])
</code></pre>
h2. 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.
<pre><code class="python">
import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template.Parse(title='senor')
'Hello senor [name]'
</code></pre>
h1(#parser). Parser class
The @Parser@ class provides simple management of multiple @Template@ objects. It is mainly used to load templates from disk. When initiating a @Parser@, the first argument provides the search path from where templates should be loaded (the default is the current working directory). An optional second argument can be provided to preload the template cache: a mapping of names and @Template@ objects.
Creating a parser object, and loading the 'example.utp' template from the 'templates' directory works like this:
<pre><code class="python">
import templateparser
>>> parser = templateparser.Parser('templates') # This sets the 'templates' directory as the search path for @AddTemplate@
>>> template = parser.AddTemplate('example.utp') # Loads the 'templates/example.utp' and stores it as 'example.utp'
>>> template.Parse(title='mister', name='Bob Dobalina')
'Hello mister Bob Dobalina'
</code></pre>
The @AddTemplate@ method takes a second optional argument, which allows us to give the template a different name in the cache. However, we have not covered using this cache yet. The @Parser@ object behaves like a slightly modified dictionary to achieve this. Retrieving keys yields the associated template. Keys that are not present in the cache are _automatically_ retrieved from the filesystem. If these cannot be found, @TemplateReadError@ is raised:
<pre><code class="python">
import templateparser
>>> parser = templateparser.Parser('templates')
>>> parser['example.utp'].Parse(title='mister', name='Bob Dobalina') # Automatically loads the template
'Hello mister Bob Dobalina'
>>> parser['bad_template.utp'].Parse(failure='imminent')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/elmer/underdark/libs/uweb/templateparser.py", line 147, in __getitem__
self.AddTemplate(template)
File "/home/elmer/underdark/libs/uweb/templateparser.py", line 171, in AddTemplate
raise TemplateReadError('Could not load template %r' % template_path)
underdark.libs.uweb.templateparser.TemplateReadError: Could not load template 'templates/bad_template.utp'
</code></pre>
h1(#using). Using TemplateParser inside µWeb
h1(#syntax). Templating language syntax
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:
* The [[TemplateParser#template|Template class]], used to parse the templating language
* The [[TemplateParser#parser|Parser class]], which provides template loading and caching
* [[TemplateParser#using|Using TemplateParser]] inside a µWeb PageMaker
* A detailed explanation of the [[TemplateParser#syntax|templating language syntax]], constructs and behaviors
First though, to help with understanding the TemplateParser, a minimal size template document:
<pre><code class="html">
Hello [title] [name]
</code></pre>
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.
h1(#template). 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.
h2. 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 [[TemplateParser#syntax|syntax]]:
<pre><code class="python">
import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])
</code></pre>
Above can be seen the various parts of the template, which will be combined to output once parsed.
h2. 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:
<pre><code class="python">
import templateparser
>>> template = templateparser.Template.FromFile('example.utp')
>>> template
Template([TemplateText('Hello '), TemplateTag('[title]'), TemplateText(' '), TemplateTag('[name]')])
</code></pre>
h2. 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.
<pre><code class="python">
import templateparser
>>> template = templateparser.Template('Hello [title] [name]')
>>> template.Parse(title='senor')
'Hello senor [name]'
</code></pre>
h1(#parser). Parser class
The @Parser@ class provides simple management of multiple @Template@ objects. It is mainly used to load templates from disk. When initiating a @Parser@, the first argument provides the search path from where templates should be loaded (the default is the current working directory). An optional second argument can be provided to preload the template cache: a mapping of names and @Template@ objects.
Creating a parser object, and loading the 'example.utp' template from the 'templates' directory works like this:
<pre><code class="python">
import templateparser
>>> parser = templateparser.Parser('templates') # This sets the 'templates' directory as the search path for @AddTemplate@
>>> template = parser.AddTemplate('example.utp') # Loads the 'templates/example.utp' and stores it as 'example.utp'
>>> template.Parse(title='mister', name='Bob Dobalina')
'Hello mister Bob Dobalina'
</code></pre>
The @AddTemplate@ method takes a second optional argument, which allows us to give the template a different name in the cache. However, we have not covered using this cache yet. The @Parser@ object behaves like a slightly modified dictionary to achieve this. Retrieving keys yields the associated template. Keys that are not present in the cache are _automatically_ retrieved from the filesystem. If these cannot be found, @TemplateReadError@ is raised:
<pre><code class="python">
import templateparser
>>> parser = templateparser.Parser('templates')
>>> parser['example.utp'].Parse(title='mister', name='Bob Dobalina') # Automatically loads the template
'Hello mister Bob Dobalina'
>>> parser['bad_template.utp'].Parse(failure='imminent')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/elmer/underdark/libs/uweb/templateparser.py", line 147, in __getitem__
self.AddTemplate(template)
File "/home/elmer/underdark/libs/uweb/templateparser.py", line 171, in AddTemplate
raise TemplateReadError('Could not load template %r' % template_path)
underdark.libs.uweb.templateparser.TemplateReadError: Could not load template 'templates/bad_template.utp'
</code></pre>
h1(#using). Using TemplateParser inside µWeb
h1(#syntax). Templating language syntax