pylons.templating – Render functions and helpers

Render functions and helpers, including legacy Buffet implementation

Render functions and helpers

pylons.templating includes several basic render functions, render_mako(), render_genshi() and render_jinja2() that render templates from the file-system with the assumption that variables intended for the will be attached to tmpl_context (hereafter referred to by its short name of c which it is commonly imported as).

The default render functions work with the template language loader object that is setup on the app_globals object in the project’s config/environment.py.

Usage

Generally, one of the render functions will be imported in the controller. Variables intended for the template are attached to the c object. The render functions return unicode (they actually return literal objects, a subclass of unicode).

Tip

tmpl_context (template context) is abbreviated to c instead of its full name since it will likely be used extensively and it’s much faster to use c. Of course, for users that can’t tolerate one-letter variables, feel free to not import tmpl_context as c since both names are available in templates as well.

Example of rendering a template with some variables:

from pylons import tmpl_context as c
from pylons.templating import render_mako as render

from sampleproject.lib.base import BaseController

class SampleController(BaseController):

    def index(self):
        c.first_name = "Joe"
        c.last_name = "Smith"
        return render('/some/template.mako')

And the accompanying Mako template:

Hello ${c.first name}, I see your lastname is ${c.last_name}!

Your controller will have additional default imports for commonly used functions.

Template Globals

Templates rendered in Pylons should include the default Pylons globals as the render_mako(), render_genshi() and render_jinja2() functions. The full list of Pylons globals that are included in the template’s namespace are:

  • c – Template context object
  • tmpl_context – Template context object
  • config – Pylons PylonsConfig object (acts as a dict)
  • g – Project application globals object
  • app_globals – Project application globals object
  • h – Project helpers module reference
  • request – Pylons Request object for this request
  • response – Pylons Response object for this request
  • session – Pylons session object (unless Sessions are removed)
  • url – Routes url generator object
  • translator – Gettext translator object configured for current locale
  • ungettext() – Unicode capable version of gettext’s ngettext function (handles plural translations)
  • _() – Unicode capable gettext translate function
  • N_() – gettext no-op function to mark a string for translation, but doesn’t actually translate

Configuring the template language

The template engine is created in the projects config/environment.py and attached to the app_globals (g) instance. Configuration options can be directly passed into the template engine, and are used by the render functions.

Warning

Don’t change the variable name on app_globals that the template loader is attached to if you want to use the render_* functions that pylons.templating comes with. The render_* functions look for the template loader to render the template.

Legacy Buffet templating plugin and render functions

The Buffet object is styled after the original Buffet module that implements template language neutral rendering for CherryPy. This version of Buffet also contains caching functionality that utilizes Beaker middleware to provide template language neutral caching functionality.

A customized version of BuffetMyghty is included that provides a template API hook as the pylonsmyghty engine. This version of BuffetMyghty disregards some of the TurboGears API spec so that traditional Myghty template names can be used with / and file extensions.

The render functions are intended as the primary user-visible rendering commands and hook into Buffet to make rendering content easy.

Module Contents

pylons.templating.pylons_globals()

Create and return a dictionary of global Pylons variables

Render functions should call this to retrieve a list of global Pylons variables that should be included in the global template namespace if possible.

Pylons variables that are returned in the dictionary:
c, g, h, _, N_, config, request, response, translator, ungettext, url

If SessionMiddleware is being used, session will also be available in the template namespace.

pylons.templating.cached_template(template_name, render_func, ns_options=(), cache_key=None, cache_type=None, cache_expire=None, **kwargs)

Cache and render a template

Cache a template to the namespace template_name, along with a specific key if provided.

Basic Options

template_name
Name of the template, which is used as the template namespace.
render_func
Function used to generate the template should it no longer be valid or doesn’t exist in the cache.
ns_options
Tuple of strings, that should correspond to keys likely to be in the kwargs that should be used to construct the namespace used for the cache. For example, if the template language supports the ‘fragment’ option, the namespace should include it so that the cached copy for a template is not the same as the fragment version of it.

Caching options (uses Beaker caching middleware)

cache_key
Key to cache this copy of the template under.
cache_type
Valid options are dbm, file, memory, database, or memcached.
cache_expire
Time in seconds to cache this template with this cache_key for. Or use ‘never’ to designate that the cache should never expire.

The minimum key required to trigger caching is cache_expire='never' which will cache the template forever seconds with no key.

pylons.templating.render_mako(template_name, extra_vars=None, cache_key=None, cache_type=None, cache_expire=None)

Render a template with Mako

Accepts the cache options cache_key, cache_type, and cache_expire.

pylons.templating.render_genshi(template_name, extra_vars=None, cache_key=None, cache_type=None, cache_expire=None, method='xhtml')

Render a template with Genshi

Accepts the cache options cache_key, cache_type, and cache_expire in addition to method which are passed to Genshi’s render function.

Legacy Render Functions

pylons.templating.render(*args, **kargs)

Render a template and return it as a string (possibly Unicode)

Optionally takes 3 keyword arguments to use caching supplied by Buffet.

Examples:

content = render('/my/template.mako')
print content
content = render('/my/template2.myt', fragment=True)

Note

Not all template languages support the concept of a fragment. In those template languages that do support the fragment option, this usually implies that the template will be rendered without extending or inheriting any site skin.

pylons.templating.render_response(*args, **kargs)

Deprecated: render_response is deprecated, please return the response content directly (via the render function) instead.

Returns the rendered response within a Response object

See render for information on rendering.

Example:

def view(self):
    return render_response('/my/template.mako')

Legacy Buffet Functions

exception pylons.templating.BuffetError
Buffet Exception
class pylons.templating.Buffet(default_engine=None, template_root=None, default_options=None, **config)

Buffet style plug-in template rendering

Buffet implements template language plug-in support modeled highly on the Buffet Project from which this class inherits its name.

prepare(engine_name, template_root=None, alias=None, **config)

Prepare a template engine for use

This method must be run before the render method is called so that the template_root and options can be set. Template engines can also be aliased if you wish to use multiplate configurations of the same template engines, or prefer a shorter name when rendering a template with the engine of your choice.

render(engine_name=None, template_name=None, include_pylons_variables=True, namespace=None, cache_key=None, cache_expire=None, cache_type=None, **options)

Render a template using a template engine plug-in

To use templates it is expected that you will attach data to be used in the template to the c variable which is available in the controller and the template.

When porting code from other projects it is sometimes easier to use an exisitng dictionary which can be specified with namespace.

engine_name
The name of the template engine to use, which must be ‘prepared’ first.
template_name
Name of the template to render
include_pylons_variables
If a custom namespace is specified this determines whether Pylons variables are included in the namespace or not. Defaults to True.
namespace
A custom dictionary of names and values to be substituted in the template.

Caching options (uses Beaker caching middleware)

cache_key
Key to cache this copy of the template under.
cache_type
Valid options are dbm, file, memory, or ext:memcached.
cache_expire
Time in seconds to cache this template with this cache_key for. Or use ‘never’ to designate that the cache should never expire.

The minimum key required to trigger caching is cache_expire='never' which will cache the template forever seconds with no key.

All other keyword options are passed directly to the template engine used.

exception pylons.templating.TemplateEngineMissing
Exception to toss when an engine is missing
class pylons.templating.MyghtyTemplatePlugin(extra_vars_func=None, options=None)

Myghty Template Plugin

This Myghty Template Plugin varies from the official BuffetMyghty in that it will properly populate all the default Myghty variables needed and render fragments.

load_template(template_path)
Unused method for TG plug-in API compatibility
render(info, format='html', fragment=False, template=None, output_encoding=None, encoding_errors=None, disable_unicode=None)
Render the template indicated with info as the namespace and globals from the info['_global_args'] key.