TurboGears - Serving Templates



An Event though HTML content can be returned to the browser, for more advanced output, the use of template engine is always preferred. In a full stack project ‘quickstarted’ by gearbox, Genshi is enabled as the default template renderer. In a minimal application, however Genshi (or any other template engine, such as jinja) needs to be installed and enabled. Genshi template engine permits to write templates in pure xhtml and validates them to detect issues at compile time and prevent serving broken pages.

Templates are referred to by using a dotted notation. In our Hello project a templates directory is provided to store template web pages. Hence sample.html will be referred as hello.templates.sample (extension not mentioned). TurboGears renders this template through an expose decorator to link controller method to it by tg.render_template() function.

The exposed controller function returns a Python dictionary object. This dictionary object is in turn passed on to the linked template. Placeholders in template are filled with dictionary values.

To begin with, let us display a web page with plain html script. The exposed controller returns a null dictionary object as we do not intend to send any data to be parsed inside the HTML script.

How to Creat a Sample HTML

Our sample.html is given below. Ensure that it is stored in templates directory of project.

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>
	
   <body>
      <h2>Hello, Welcome to TurboGears!.</h2>
   </body>
</html>

Add sample() function in root.py and expose sample.html through it.

@expose("hello.templates.sample")
   def sample(self):
      return {}

The following result will be displayed in the browser when a URL http://localhost:8080/sample is entered after starting the web server.

Display Result

As mentioned above, a dictionary object is sent as collection of parameters to a Genshi template. This template contains ‘place holders’, which are dynamically filled with parameters received from the controller.

Let us change the sample() function to send a dictionary object to the sample template.

@expose("hello.templates.sample")
   def sample(self,name):
      mydata = {'person':name}
      return mydata

Create sample.html in templates folder (templates\sample.html)

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>
	
   <body>
      <h2>Hello, my name is ${person}!.</h2>
   </body>
</html>

In the above HTML code, ${person} is the placeholder. Enter http://localhost:8080/sample?name=MVL as URL in the browser. This URL is mapped to sample() method in our root controller. It returns a dictionary object. This is picked by linked template page sample.html in templates directory. The ${person} is then substituted by MVL in the web page.

It is also possible to access the HTML form data in a controller function. HTML form uses to send form data.

Result
Advertisements