Simple tutorial on using the Mako Template Library in Python, pythonmako Template Library

Source: Internet
Author: User

Simple tutorial on using the Mako Template Library in Python, pythonmako Template Library

Mako is a high-performance Python template library. Its syntax and API use many other template libraries, such as Django and Jinja2.
Basic usage

The most basic method to create a Template and render it is to use the Template class:
 

from mako.template import Templatet = Template('hello world!')print t.render()

The text parameters passed to the Template are compiled into a Python module. The module contains an render_body () function that generates the template output. When calling the render () method, Mako creates a template runtime environment, calls the render_body () function, saves the output to the buffer, and returns its string content.
The render_body () function can access a variable set. You can send additional keyword parameters to the render () method to specify these variables:
 

from mako.template import Templatet = Template('hello, ${name}!')print t.render(name='yeolar')

The render () method allows Mako to create a Context object, which stores all variables that can be accessed by the template and a buffer used to save the output. You can also create a Context by yourself and use the render_context () method to make the template use it for rendering:
 

from mako.template import Templatefrom mako.runtime import Contextfrom StringIO import StringIOt = Template('hello, ${name}!')buf = StringIO()c = Context(buf, name='yeolar')t.render_context(c)print buf.getValue()

Use a file template

Template can also be loaded from a file, using the filename parameter:
 

from mako.template import Templatet = Template(filename='/docs/tpl.txt')print t.render()

To improve performance, the Template loaded from the file can also cache the generated module into a general Python module file (. py file) in the file system, which is achieved by adding the module_directory parameter:

from mako.template import Templatet = Template(filename='/docs/tpl.txt', module_directory='/tmp/mako_modules')print t.render()

After the above Code is rendered, a/tmp/mako_modules/docs/tpl.txt. py file is created, which contains the module source code. The module File is automatically reused when a Template with the same parameters is created next time.
Use TemplateLookup

All examples are related to the usage of a single Template object. If the code in the template is to locate other template resources, you need some method to use URI to find them. This requirement is met by the TemplateLookup class. This class is constructed by passing in a Template to find the list of directories, and then passed as a keyword parameter to the Template object:
 

from mako.template import Templatefrom mako.lookup import TemplateLookuplookup = TemplateLookup(directories=['/docs'])t = Template('<%include file="header.txt" /> hello word!', lookup=lookup)

The created template contains the file header.txt. In order to find header.txt, A TemplateLookup object is passed to it.
Generally, an application stores most or all of the templates in the file system as text files. A real application gets its template directly from TemplateLookup and uses the get_template () method. It accepts the URI of the template as the parameter:
 

from mako.template import Templatefrom mako.lookup import TemplateLookuplookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules')def serve_template(t_name, **kwargs):  t = lookup.get_template(t_name)  print t.render(**kwargs)

In the above example, A TemplateLookup is created, which searches for the template from the/docs directory and stores all the module files in the/tmp/mako_modules directory. Attaches the imported URI to each search directory to locate the template. For example, If/etc/beans/info.txt is passed, the search file/docs/etc/beans/info.txt is located, topLevelNotFound exception will be thrown if not found.
When the Template is located, the URI passed to get_template () will also be used as the uri attribute of the Template. Template uses this URI to obtain the name of the module File. Therefore, in the above example,/etc/beans/info.txt will create the module File/tmp/mako_modules/etc/beans/info.txt. py.
Set the collection size

TemplateLookup can also set the total number of cached templates in the memory to a fixed value. By default, the TemplateLookup size is unlimited. You can use the collection_size parameter to specify a fixed value:
 

lookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules', collection_size=500)

In the above lookup, the maximum number of templates loaded into the memory is 500. Then, it uses the LRU policy to clear and replace the template.
Set File System check

Another important sign of TemplateLookup is filesystem_checks. The default value is True. Each time the get_template () method returns a template, the modification time of the original template file and the last loading time of the template are compared. If the file is updated, the template is reloaded and compiled. In the production system, setting filesystem_checks to False can improve the performance.
Use Unicode and encoding

You can set output_encoding and encoding_errors parameters for Template and TemplateLookup to encode the output to the encoding format supported by Python:
 

from mako.template import Templatefrom mako.lookup import TemplateLookuplookup = TemplateLookup(directories=['/docs'], output_encoding='utf-8', encoding_errors='replace')t = lookup.get_template('foo.txt')print t.render()

When Python 3 is used, if output_encoding is set, the render () method returns a bytes object; otherwise, a string is returned.
The render_unicode () method returns the template output as a Python unicode object, and Python 3 is a string:
 

print t.render_unicode()

The preceding method does not have an output encoding parameter. You can encode it yourself:
 

print t.render_unicode().encode('utf-8', 'replace')

Note that the underlying output stream of the template in Mako is a Python Unicode object.
Exception Handling

Template exceptions may occur in two places. One is when you search, parse, and compile a template, and the other is when you run the template. If an exception occurs during template running, it is thrown in the problematic Python code. Mako has its own set of exception classes, which are mainly used in the search and compilation stages of Template Construction. Mako provides some library routines to provide Mako information for the exception stack and output exceptions in text or HTML format. Python file names, row numbers, and code snippets are converted into Mako template file names, row numbers, and code snippets. The row of the Mako template module is converted to the corresponding row of the original template file.

Text_error_template () and html_error_template () functions are used to format exception tracking. They use sys. exc_info () to obtain the recently thrown exception. These processors are used as follows:
 

From mako import exceptionstry: t = lookup. get_template (uri) print t. render () failed T: print exceptions. text_error_template (). render () or render as HTML: from mako import predictionstry: t = lookup. get_template (uri) print t. render () failed T: print exceptions.html _ error_template (). render ()

The html_error_template () template accepts two options: Specify full = False to render only the section of HTML, and specify css = False to disable the default style sheet. For example:
 

print exceptions.html_error_template().render(full=False)

The HTML Rendering function can also be added to the Template with the format_exceptions flag. In this case, any exceptions in the rendering phase of the template will be replaced with the output of html_error_template:
 

t = Template(filename='/foo/bar', format_exceptions=True)print t.render()

Note that no output stream is defined when the Template is constructed during the compilation phase of the Template above. Therefore, exceptions in the search, parsing, and compilation phases will not be processed normally, but will be propagated. The trace before rendering does not include rows in the Mako form, which means that exceptions before rendering and during rendering are processed in different ways, so try/try t may be more common.

The error template function uses the RichTraceback object as the underlying object. This object can also be used directly to provide custom error views. The following is an example:
 

from mako.exceptions import RichTracebacktry:  t = lookup.get_template(uri)  print t.render()except:  traceback = RichTraceback()  for (filename, lineno, function, line) in traceback.traceback:    print 'File %s, line %s, in %s' % (filename, lineno, function)    print line, '\n'  print '%s: %s' % (str(traceback.error.__class__.__name__), traceback.error)

Integrate Mako
Integrate Mako in Django

The middleware of Django can be integrated with Mako. First, install the django-mako module.
In the settings. py file of the Django project, modify MIDDLEWARE_CLASSES and add djangomako. middleware. MakoMiddleware. You can use the render_to_response () function:
 

from djangomako.shortcuts import render_to_responsedef hello_view(request):  return render_to_response('hello.txt', {'name': 'yeolar'})

Integrate Mako in Tornado

You can use Mako directly in Tornado. The following is an example:

import tornado.webimport mako.lookupimport mako.templateLOOK_UP = mako.lookup.TemplateLookup(    directories=[TEMPLATE_PATH], module_directory='/tmp/mako',    output_encoding='utf-8', encoding_errors='replace')class BaseHandler(tornado.web.RequestHandler):  def initialize(self, lookup=LOOK_UP):    '''Set template lookup object, Defalut is LOOK_UP'''    self._lookup = lookup  def render_string(self, filename, **kwargs):    '''Override render_string to use mako template.    Like tornado render_string method, this method    also pass request handler environment to template engine.    '''    try:      template = self._lookup.get_template(filename)      env_kwargs = dict(        handler = self,        request = self.request,        current_user = self.current_user,        locale = self.locale,        _ = self.locale.translate,        static_url = self.static_url,        xsrf_form_html = self.xsrf_form_html,        reverse_url = self.application.reverse_url,        )      env_kwargs.update(kwargs)      return template.render(**env_kwargs)    except:      # exception handler      pass  def render(self, filename, **kwargs):    self.finish(self.render_string(filename, **kwargs))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.