Templayer %version% Tutorial

Templayer Home Page / Tutorial / Reference

%toc_left% %toc_right%
{contents}

Templayer Tutorial Template File

This file is used by docgen_tutorial.py to generate the tutorial documentation tutorial.html.


Items in the list that follows are parsed by docgen_tutorial.py. Each item has a tag and a name, separated by a tab character. Items without tags are new sections. A --- separates the left and right columns in the table of contents.
Tag	Section or Item Name
{section_data}
	CGI Script: Gordon's Lawn Happenings
lawn1	Static HTML (before using Templayer)
lawn2	Minimal Templayer Template
lawn3	Using Slots
lawn4	Using a Simple Layer
lawn5	Using Nested Layers
lawn6	Advanced Nested Layers
---
	Django Applications and Templayer
simple.templayer	Simple Views
book.templayer	Forms
emulate.templayer	Emulating Django Templates
{/section_data}

{toc_section}

%snum%. %name%
{/toc_section}

{toc_item}

%snum%.%inum%. %name%
{/toc_item}

{section_head}

%snum%. %name%

{/section_head}
{section_body}

%snum%.%inum%. %name% [back to top]

%contents%

{/section_body}
{html_example}
%name%
%contents%
{/html_example}
{code_example}
%name%
%contents%
{/code_example}
{result}
%contents%
{/result}
{body[lawn1]}

Our examples will be based on a single-page web site:

%html% %result[0]%

All the example source code may be extracted from the docgen_tutorial.py script that is included with Templayer by running:

python docgen_tutorial.py -s

{/body[lawn1]}
{body[lawn2]}

The first thing we need to do to use this page as a Templayer template file is to add "{contents}" and "{/contents}" labels to the file:

%html%

Templayer searches the template file for the first occurrence of "{contents}" and the last occurrence of "{/contents}". This splits the file into header, contents and footer.

The header and footer will appear in Templayer's output. The contents is described in sections below.

%code[0]%

This is a minimal CGI script that uses Templayer to display the web site. The result of running this script will be the same as if we just used the static page above.

We first create an HTMLTemplate object to handle parsing of the template above.

The start_file function creates a FileWriter object that will use the our HTMLTemplate object. The FileWriter object handles a single output run for our template. The start_file function allows you to pass in a file-like object to use instead of the standard output. For a CGI script we use the default.

The FileWriter object's open function will be explained below.

No output is written until the close function is called at the end of the script. If you don't get any output from your script it might be because you forgot to call the close function on your FileWriter object.

{/body[lawn2]}
{body[lawn3]}

The next step is to add slots to the header and footer of the template. Slots are like variables that can be filled in by the application. In the template file slot names are wrapped in "%" characters:

%html%

We have added two %title% slots to the header and one %date% slot to the footer of this template.

Please note: "%" is not a special character in Templayer templates. You do not need to escape "%" characters that aren't part of a slot. When filling slots Templayer has a list of slot names and it only replaces those slots, leaving all the other "%" characters in the template intact.

%code[0]%

Essentially only one line has changed in the code. The open function takes keyword parameters where the names of the parameters correspond to slots in the header and footer. Here both %title% slots will be filled with "Gordon's Lawn Happenings", and the %date% slot will be filled with the current date and time.

The values passed in to fill slots are interpreted by our HTMLTemplate object. The HTMLTemplate object expects HTML Markup described by the expand_html_markup function. Plain strings are treated as unsafe in HTML Markup and any characters that might be interpreted as HTML are escaped by this function. This means that Templayer's default behaviour is to escape values being filled into HTML templates.

%result[0]% {/body[lawn3]}
{body[lawn4]}

Now we look at what we can do with the content of a template file. You will recall that this refers to everything between the first occurrence of "{contents}" and the last occurrence of "{/contents}" in the template file.

%html%

We have now added a {report} layer to the template, and we have removed the "Lawn Happenings" from the template so that the application can fill them in. Layers are placed one after the next in the template content. The {report} layer extends from the first occurrence of "{report}" to the last occurrence of "{/report}" in the template content. Layers have slots just like the template header and footer.

Splitting HTML into separate layers lets us reuse the layers throughout the generated HTML, consolidating duplicated layout information. This template format can also be loaded in a web browser to test changes without running the application. Most templates can also be validated for compliance with HTML and CSS specs.

%code[0]%

We are now storing the return value of our FileWriter object's open function. The return value is a Layer object that represents the whole file. It knows the value of the header and footer which were filled in the FileWriter object's open function, but it can still have text filled into its content between the header and footer.

Layer objects have a write_layer function that is passed a layer name followed by keyword parameters that correspond to slots in that layer. Here we are adding two instances of our {report} layer to the content of the template's main Layer object. Recall that values passed in to fill slots are interpreted as HTML Markup by the expand_html_markup function. The "happenings" lists are escaped, then concatenated by this function.

Of course, we can separate the "Lawn Happenings" data from the code by creating a structure for it:

%code[1]%

This structure is a list of (day, happenings) tuples that is iterated through in the script. The day and happenings values are treated as HTML Markup

%result[0]%

Unfortunately, the HTML code that this generates is different than before we added the {report} layer — the "Happenings" are no longer in separate paragraphs. One way to fix this is to use HTML Markup and avoid mixing actual HTML into the code:

%code[2]%

The expand_html_markup function will take the ('p', text) tuples, escape the text, wrap them in HTML paragraph tags then concatenate them.

%result[1]% {/body[lawn4]}
{body[lawn5]}

HTML Markup is not intended for anything beyond very simple formatting. A more flexible solution is to create another layer to nest within the first.

%html%

Now the decision to format individual "Happenings" as paragraphs has been moved to the template in a {happening} layer.

%code[0]%

Within the new inner loop we are calling our HTMLTemplate object's format function. This function is similar to the write_layer function except that it returns a RawHTML object instead of adding it to the content of a Layer object. The expand_html_markup function will leave the contents of the RawHTML object intact, so we can use this object within HTML Markup.

{/body[lawn5]}
{body[lawn6]}

Since it is common to nest layers in Templayer another method is provided that is similar to FileWriter's open function. First we need to rename a slot in the {report} to %contents%:

%html%

Now that we have a %contents% slot we can "open" this layer and write into it:

%code[0]%

The Layer object has an open_layer function that returns a new layer object. In this case the new Layer object represents a {report} layer that is being written. The Layer object stores everything above the %contents% slot as its header and everything below as its footer. It can have text filled into its content in the same way as our main Layer object. Here we are now using write_layer to fill {happening} layers into {report} layers.

We also renamed the slot in {happening} to %contents%, so we can use the open_layer function on that as well:

%code[1]%

We want to send text into this new Layer object, so instead of calling write_layer we call the write function. It takes a single parameter that is interpreted as HTML Markup.

When using Templayer to produce very large files, or when parts of an HTML page take longer to complete, you might want to flush your output part of the way through:

%code[2]%

Layer objects have a close_child function that forces any open "child" layers to finalize their output. In this code we are closing the {report} layer. FileWriter objects have a flush function that will send all the output possible. We are first closing our {report} layer so that when we flush the output the whole report will appear.

{/body[lawn6]}
{body[simple.templayer]}

Templayer has a number of functions that help integrate with the Django Web Framework. This is an example of a simple Django view. All the examples below assume you are starting from a working project. See the Django documentation about setting up a project.

First place this Templayer template in your project's template directory:

%html%

Then we can use get_django_template function to find the template in the project's template directory without having to hard-code the system path in our view:

%code[0]%

For this type view function you may also use the django_view decorator. It takes care of creating and cleaning up the file writer object so that you don't need to "import HttpResponse" or remember to "return file_writer.close()" in every view function:

%code[1]% {/body[simple.templayer]}
{body[book.templayer]}

Templayer includes a django_form helper function for working with forms. This function converts a form object to a dictionary of fields suitable for passing to the format, open_layer or write_layer functions:

Start with models like the following:

%code[0]%

This template has two slots for each visible field in the form, one for the HTML input field and one for errors related to that field.

%html%

This code will populate the form widgets, accept input and redisplay the data (with errors if applicable) when the user clicks "Submit":

%code[1]%
Guest Book

Sign the guestbook

Your Name:
Rate the site:
Your Comments:

{/body[book.templayer]} {body[emulate.templayer]}

Existing or third-party Django applications will expect to use the standard Django templating library. To use these applications with Templayer we need to extend the Django template loader and processing mechanism to emulate Django's templates.

This example will show how to use Templayer to create a 404 page and use the "flatpages" application.

First add the django_template_loader to the TEMPLATE_LOADERS in your project's settings.py file:

Your Django project's settings.py
...
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
...
    'templayer.django_template_loader',
)
...

Also make sure that the "flatpages" application is installed. See the Django flatpages app documentation for details.

Next copy this template into the project's template directory:

%html%

Templayer's Django template emulation will look for a module named "templayer_pages.py" in the template directories when trying to load templates. The django_template decorator defines the Django template name that a function will handle. The function may take parameters with names matching values you know will be present in the context dictionary and the decorator will fill in those values for you.

Put this module in the template directory:

%code[0]%

Now the 404 handler and the flatpages application will be formatted by Templayer.

{/body[emulate.templayer]}
{/contents}