Я переопределил метод "create" класса tg.renderers.jinja.JinjaRenderer
конфиг / Jinja.py
try:
import jinja2
except ImportError: # pragma: no cover
jinja2 = None
if jinja2 is not None:
from jinja2.loaders import FileSystemLoader
from jinja2 import ChoiceLoader, Environment
from jinja2.filters import FILTERS
from jinja2.exceptions import TemplateNotFound
else: # pragma: no cover
class FileSystemLoader(object):
pass
from tg.renderers.base import RendererFactory
from tg.renderers.jinja import JinjaRenderer as jr
from tg.renderers.jinja import DottedTemplateLoader
from tg.i18n import ugettext, ungettext
class JinjaRenderer(jr):
@classmethod
def create(cls, config, app_globals):
"""Setup a renderer and loader for Jinja2 templates."""
if jinja2 is None: # pragma: no cover
return None
if config.get('use_dotted_templatenames', True):
TemplateLoader = DottedTemplateLoader
template_loader_args = {'dotted_finder': app_globals.dotted_filename_finder}
else:
TemplateLoader = FileSystemLoader
template_loader_args = {}
if not 'jinja_extensions' in config:
config['jinja_extensions'] = []
# Add i18n extension by default
if not "jinja2.ext.i18n" in config['jinja_extensions']:
config['jinja_extensions'].append("jinja2.ext.i18n")
if not 'jinja_filters' in config:
config['jinja_filters'] = {}
loader = ChoiceLoader(
[TemplateLoader(path, **template_loader_args) for path in config['paths']['templates']])
def my_finalize(thing):
return thing if thing is not None else ''
jinja2_env = Environment(loader=loader, autoescape=True, finalize=my_finalize,
auto_reload=config['auto_reload_templates'],
extensions=config['jinja_extensions'])
# Try to load custom filters module under app_package.lib.templatetools
try:
if not config['package_name']:
raise AttributeError()
filter_package = config['package_name'] + ".lib.templatetools"
autoload_lib = __import__(filter_package, {}, {}, ['jinja_filters'])
try:
autoload_filters = dict(
map(lambda x: (x, autoload_lib.jinja_filters.__dict__[x]),
autoload_lib.jinja_filters.__all__)
)
except AttributeError: # pragma: no cover
autoload_filters = dict(
filter(lambda x: callable(x[1]),
autoload_lib.jinja_filters.__dict__.iteritems())
)
except (ImportError, AttributeError):
autoload_filters = {}
# Add jinja filters
filters = dict(FILTERS, **autoload_filters)
filters.update(config['jinja_filters'])
jinja2_env.filters = filters
# Jinja's unable to request c's attributes without strict_c
config['tg.strict_tmpl_context'] = True
# Add gettext functions to the jinja environment
jinja2_env.install_gettext_callables(ugettext, ungettext)
return {'jinja': cls(jinja2_env)}
Затем в config / app_cfg.py
from Jinja import JinjaRenderer
base_config.register_rendering_engine(JinjaRenderer)
Модифицированный код
def my_finalize(thing):
return thing if thing is not None else ''
jinja2_env = Environment(loader=loader, autoescape=True, finalize=my_finalize,
auto_reload=config['auto_reload_templates'],
extensions=config['jinja_extensions'])