# Templayer 1.5.1 Tutorial

Templayer Home Page / Tutorial / Reference

1. CGI Script: Gordon's Lawn Happenings 1.1. Static HTML (before using Templayer) 1.2. Minimal Templayer Template 1.3. Using Slots 1.4. Using a Simple Layer 1.5. Using Nested Layers 1.6. Advanced Nested Layers | 2. Django Applications and Templayer 2.1. Simple Views 2.2. Forms 2.3. Emulating Django Templates

## 1. CGI Script: Gordon's Lawn Happenings

### 1.1. Static HTML (before using Templayer) [back to top]

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

lawn1.html

    <html>
    <head><title>Gordon's Lawn Happenings</title></head>
    <body>
    <h1>Gordon's Lawn Happenings</h1>
    <h3>Sunday</h3>
    <p>We've got a groundhog.  I will have to stay alert.</p>
    <p>I lost half a tomato plant to that furry guy.</p>
    <h3>Monday</h3>
    <p>The grass grew - I saw it.</p>
    </body>
    </html>

Gordon's Lawn Happenings

# Gordon's Lawn Happenings

### Sunday

We've got a groundhog. I will have to stay alert.

I lost half a tomato plant to that furry guy.

### Monday

The grass grew - I saw it.

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

### 1.2. Minimal Templayer Template [back to top]

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:

lawn2.html

    <html>
    <head><title>Gordon's Lawn Happenings</title></head>
    <body>
    <h1>Gordon's Lawn Happenings</h1>
    {contents}

    {/contents}
    <h3>Sunday</h3>
    <p>We've got a groundhog.  I will have to stay alert.</p>
    <p>I lost half a tomato plant to that furry guy.</p>
    <h3>Monday</h3>
    <p>The grass grew - I saw it.</p>
    </body>
    </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.

lawn2.py

    import templayer
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    tmpl = templayer.HTMLTemplate("lawn2.html")
    file_writer = tmpl.start_file()
    file_writer.open()
    file_writer.close()

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.

### 1.3. Using Slots [back to top]

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:

lawn3.html

    <html>
    <head><title>%title%</title></head>
    <body>
    <h1>%title%</h1>
    {contents}

    {/contents}
    <h3>Sunday</h3>
    <p>We've got a groundhog.  I will have to stay alert.</p>
    <p>I lost half a tomato plant to that furry guy.</p>
    <h3>Monday</h3>
    <p>The grass grew - I saw it.</p>

    <hr>
    <p>Generated on %date%.</p>
    </body>
    </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.

lawn3.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    tmpl = templayer.HTMLTemplate("lawn3.html")
    file_writer = tmpl.start_file()
    file_writer.open(title="Gordon's Lawn Happenings",
    		date=time.asctime())
    file_writer.close()

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.

Gordon's Lawn Happenings

# Gordon's Lawn Happenings

### Sunday

We've got a groundhog. I will have to stay alert.

I lost half a tomato plant to that furry guy.

### Monday

The grass grew - I saw it.

Generated on Sat Oct 24 03:49:22 2015.

### 1.4. Using a Simple Layer [back to top]

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.

lawn4.html

    <html>
    <head><title>%title%</title></head>
    <body>
    <h1>%title%</h1>
    {contents}

    {report}
    <h3>%day%</h3>
    %happenings%
    {/report}

    {/contents}
    <hr>
    <p>Generated on %date%.</p>
    </body>
    </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.

lawn4a.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    tmpl = templayer.HTMLTemplate("lawn4.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    main_layer.write_layer('report', day="Sunday", happenings=[
    	"We've got a groundhog.  I will have to stay alert.",
    	"I lost half a tomato plant to that furry guy."])
    main_layer.write_layer('report', day="Monday", happenings=[
    	"The grass grew - I saw it."])
    file_writer.close()

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:

lawn4b.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', ["We've got a groundhog.  I will have to stay alert.",
    	"I lost half a tomato plant to that furry guy."]),
    	('Monday', ["The grass grew - I saw it."]),
    ]

    tmpl = templayer.HTMLTemplate("lawn4.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	main_layer.write_layer('report', day=d, happenings=h)
    file_writer.close()

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

Gordon's Lawn Happenings

# Gordon's Lawn Happenings

### Sunday

We've got a groundhog. I will have to stay alert.I lost half a tomato plant to that furry guy.

### Monday

The grass grew - I saw it.

Generated on Sat Oct 24 03:49:22 2015.

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:

lawn4c.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', [('p',"We've got a groundhog.  I will have to stay alert."),
    		('p',"I lost half a tomato plant to that furry guy.")]),
    	('Monday', [('p',"The grass grew - I saw it.")]),
    ]

    tmpl = templayer.HTMLTemplate("lawn4.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	main_layer.write_layer('report', day=d, happenings=h)
    file_writer.close()

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

Gordon's Lawn Happenings

# Gordon's Lawn Happenings

### Sunday

We've got a groundhog. I will have to stay alert.

I lost half a tomato plant to that furry guy.

### Monday

The grass grew - I saw it.

Generated on Sat Oct 24 03:49:22 2015.

### 1.5. Using Nested Layers [back to top]

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.

lawn5.html

    <html>
    <head><title>%title%</title></head>
    <body>
    <h1>%title%</h1>
    {contents}

    {report}
    <h3>%day%</h3>
    %happenings%
    {/report}

    {happening}<p>%what%</p>
    {/happening}

    {/contents}
    <hr>
    <p>Generated on %date%.</p>
    </body>
    </html>

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

lawn5.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', ["We've got a groundhog.  I will have to stay alert.",
    		"I lost half a tomato plant to that furry guy."]),
    	('Monday', ["The grass grew - I saw it."]),
    ]

    tmpl = templayer.HTMLTemplate("lawn5.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	happening_list = []
    	for w in h:
    		formatted = tmpl.format('happening', what=w)
    		happening_list.append(formatted)
    	main_layer.write_layer('report', day=d, happenings=happening_list)
    file_writer.close()

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.

### 1.6. Advanced Nested Layers [back to top]

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%:

lawn6.html

    <html>
    <head><title>%title%</title></head>
    <body>
    <h1>%title%</h1>
    {contents}

    {report}
    <h3>%day%</h3>
    %contents%
    {/report}

    {happening}<p>%contents%</p>
    {/happening}

    {/contents}
    <hr>
    <p>Generated on %date%.</p>
    </body>
    </html>

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

lawn6a.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', ["We've got a groundhog.  I will have to stay alert.",
    		"I lost half a tomato plant to that furry guy."]),
    	('Monday', ["The grass grew - I saw it."]),
    ]

    tmpl = templayer.HTMLTemplate("lawn6.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	report_layer = main_layer.open_layer('report', day=d)
    	for happening in h:
    		report_layer.write_layer('happening', contents=happening)
    file_writer.close()

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:

lawn6b.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', ["We've got a groundhog.  I will have to stay alert.",
    		"I lost half a tomato plant to that furry guy."]),
    	('Monday', ["The grass grew - I saw it."]),
    ]

    tmpl = templayer.HTMLTemplate("lawn6.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	report_layer = main_layer.open_layer('report', day=d)
    	for happening in h:
    		happening_layer = report_layer.open_layer('happening')
    		happening_layer.write(happening)
    file_writer.close()

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:

lawn6c.py

    import templayer
    import time
    import sys

    sys.stdout.write("Content-type: text/html\r\n\r\n")

    reports = [
    	('Sunday', ["We've got a groundhog.  I will have to stay alert.",
    		"I lost half a tomato plant to that furry guy."]),
    	('Monday', ["The grass grew - I saw it."]),
    ]

    tmpl = templayer.HTMLTemplate("lawn6.html")
    file_writer = tmpl.start_file()
    main_layer = file_writer.open(title="Gordon's Lawn Happenings",
    	date=time.asctime())
    for d, h in reports:
    	report_layer = main_layer.open_layer('report', day=d)
    	for happening in h:
    		happening_layer = report_layer.open_layer('happening')
    		happening_layer.write(happening)
    	main_layer.close_child()
    	file_writer.flush()
    file_writer.close()

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.

## 2. Django Applications and Templayer

### 2.1. Simple Views [back to top]

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:

simple.templayer.html

    <html>
    <head><title>%title%</title></head>
    <body>

    <h1>%title%</h1>
    {contents}

    {/contents}
    </body>
    </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:

simple_views_1.py

    from django.http import HttpResponse
    import datetime
    import templayer

    tmpl = templayer.get_django_template("simple.templayer.html")

    def current_datetime(request):
    	file_writer = tmpl.start_file(HttpResponse())
    	now = datetime.datetime.now()
    	contents = file_writer.open(title="Current Date and Time")
    	contents.write("It is now %s." % now)
    	return file_writer.close()

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:

simple_views_2.py

    import datetime
    import templayer

    tmpl = templayer.get_django_template("simple.templayer.html")

    @templayer.django_view(tmpl)
    def current_datetime(file_writer, request):
    	now = datetime.datetime.now()
    	contents = file_writer.open(title="Current Date and Time")
    	contents.write("It is now %s." % now)

### 2.2. Forms [back to top]

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:

book_models.py

    from django.db import models

    RATING_CHOICES = (
    	('G', "Great!"),
    	('A', "Average"),
    	('U', "Uninteresting"),
    )

    class Entry(models.Model):
    	name = models.CharField("Your Name", max_length=100)
    	rating = models.CharField("Rate this site", max_length=1,
    		choices=RATING_CHOICES)
    	comment = models.TextField("Your Comments (optional)", blank=True)
    	posted = models.DateTimeField(auto_now_add=True)

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.

book.templayer.html

    <html>
    <head><title>%title%</title></head>
    <body>

    <h1>%title%</h1>
    {contents}

    {new_entry}
    <form method="POST">
    <h2>Sign the guestbook</h2>
    Your Name: %form.name% %form.name.errors%<br/>
    Rate the site: %form.rating% %form.rating.errors%<br/>
    Your Comments:<br/>
    %form.comment% %form.comment.errors%<br/>
    <input type="submit" value="Submit"/>
    </form>
    {/new_entry}

    {/contents}
    </body>
    </html>

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

book_views.py

    from book.models import Entry
    from django.forms import ModelForm

    import templayer

    tmpl = templayer.get_django_template("book.templayer.html")

    class EntryForm(ModelForm):
    	class Meta:
    		model = Entry

    @templayer.django_view(tmpl)
    def guest_book(file_layer, request):
    	if request.POST:
    		entry_form = EntryForm(request.POST)
    		# TODO: do something with the data if all is well
    	else:
    		entry_form = EntryForm()
    	contents = file_writer.open(title="Guest Book")
    	contents.write_layer("new_entry", **templayer.django_form(entry_form))

Guest Book

##

    Sign the guestbook
    Your Name:

    Rate the site:

    Your Comments:

### 2.3. Emulating Django Templates [back to top]

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:

emulate.templayer.html

    <html>
    <head><title>%title%</title></head>
    <body>

    <h1>%title%</h1>
    {contents}

    {show_404}
    The url %url% could not be found.
    {/show_404}

    {flatpage_body}
    %contents%
    {/flatpage_body}

    {/contents}
    </body>
    </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:

templayer_pages.py

    import templayer

    tmpl = templayer.get_django_template("emulate.templayer.html")

    @templayer.django_template(tmpl, "404.html")
    def show_404(file_writer, context, request_path):
    	contents = file_writer.open(title="Page not found")

    	# request_path == context['request_path']
    	contents.write_layer("show_404", url=request_path)

    @templayer.django_template(tmpl, "flatpages/default.html")
    def show_flatpage(file_writer, context, flatpage):
    	contents = file_writer.open(title=flatpage.title)
    	fp_contents = contents.open_layer("flatpage_body")

    	# the flatpage content is HTML, so don't escape it.
    	fp_contents.write(templayer.RawHTML(flatpage.content))

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