[ jinja2 ] render template

Example

import jinja2

 

path_to_template = '/path/to/templates'

env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path_to_template)), extensions=['jinja2.ext.i18n'])

env.install_gettext_callables(_gettext, _ngettext) # for i18n extensions, Installs the given gettext and ngettext callables into the environment as globals. They are supposed to behave exactly like the standard library’s gettext.ugettext() and gettext.ungettext() functions.

t = env.from_string(open(path_to_template).read()) # Load a template from a string. This parses the source given and returns a Template object

row = {'foo': 'bar'}

body = t.render(**row)

 

_gettext and _ngettext are declared below

def _gettext(text):

return text

def _ngettext(singular, plural, n):

pass

• gettext: translate a single string
• ngettext: translate a pluralizable string

 

Actually above example works, but the below example shows better picture of how FileSystemLoader works.

template_env = jinja2.Environment(loader=jinja2.FileSystemLoader('mydir'))
template_env.get_template('foo/bar.html')

 

ref : http://jinja.pocoo.org/docs/2.9/api/,

http://jinja.pocoo.org/docs/2.9/extensions/#jinja-extensions,

https://stackoverflow.com/questions/9641317/jinja2-filesystemloader-load-all-subdirectories

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s