Source code for bag.web.pyramid.apps.views
"""Useful base views, functions and decorators for Pyramid."""
from typing import Any, Dict # noqa
from pyramid.decorator import reify
from pyramid.i18n import get_localizer
from pyramid.renderers import get_renderer
from pyramid.url import route_url
from bag.settings import asbool
from bag.text import uncommafy
[docs]class BaseView:
"""Base class for views."""
def __init__(self, request):
self.request = request
[docs] @reify
def tr(self):
"""The translator of the localizer of this request."""
return get_localizer(self.request).translate
[docs] def url(self, name, *a, **kw):
"""A route_url that is easier to use."""
return route_url(name, self.request, *a, **kw)
undefined = object()
[docs]class ChameleonBaseView:
"""Base view mixin class for projects that use Chameleon with macros."""
macro_cache = {} # type: Dict[str, Any] # for Chameleon template macros
[docs] def macro(self, template, macro_name):
"""Load macros from any Chameleon template.
If settings['reload_templates'] is false, also memoize the macros.
"""
if asbool(self.request.registry.settings.get('reload_templates')):
return get_renderer(template).implementation().macros[macro_name]
else:
macro_path = template + '|' + macro_name
macro = self.macro_cache.get(macro_path)
if not macro:
self.macro_cache[macro_path] = macro = \
get_renderer(template).implementation().macros[macro_name]
return macro