This module provides Jinja2 template support for webapp2.
To use it, you must add the jinja2
package to your application
directory (for App Engine) or install it in your virtual environment
(for other servers).
You can download jinja2
from PyPi:
Learn more about Jinja2:
webapp2_extras.jinja2.
default_config
= {'template_path': 'templates', 'force_compiled': False, 'globals': None, 'filters': None, 'environment_args': {'autoescape': True, 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']}, 'compiled_path': None}¶Default configuration values for this module. Keys are:
jinja2.ext.autoescape
and jinja2.ext.with_
. For production it
may be a good idea to set ‘auto_reload’ to False – we don’t need to
check if templates changed after deployed.webapp2_extras.jinja2.
Jinja2
(app, config=None)[source]¶Wrapper for configurable and cached Jinja2 environment.
To used it, set it as a cached property in a base RequestHandler:
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
Then extended handlers can render templates directly:
class MyHandler(BaseHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('my_template.html', **context)
__init__
(app, config=None)[source]¶Initializes the Jinja2 object.
Parameters: |
|
---|
get_template_attribute
(filename, attribute)[source]¶Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _foo.html with the following contents:
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this:
hello = get_template_attribute('_foo.html', 'hello')
return hello('World')
This function comes from Flask.
Parameters: |
|
---|
render_template
(_filename, **context)[source]¶Renders a template and returns a response object.
Parameters: |
|
---|---|
Returns: | A rendered template. |
webapp2_extras.jinja2.
get_jinja2
(factory=<class 'webapp2_extras.jinja2.Jinja2'>, key='webapp2_extras.jinja2.Jinja2', app=None)[source]¶Returns an instance of Jinja2
from the app registry.
It’ll try to get it from the current app registry, and if it is not registered it’ll be instantiated and registered. A second call to this function will return the same instance.
Parameters: |
|
---|
webapp2_extras.jinja2.
set_jinja2
(jinja2, key='webapp2_extras.jinja2.Jinja2', app=None)[source]¶Sets an instance of Jinja2
in the app registry.
Parameters: |
|
---|