DBに格納したmakoテンプレートをレンダリングする(2)

結局、次のように実装しました。

# -*- coding: utf-8 -*-
import inspect
import pylons
from pylons.templating import render
from mako.template import Template
from mako.lookup import TemplateLookup

class MakoStringProcessor(object):
    """
    render string with mako engine

    options:
    * directories
    * module_directory
    * default_filters
    * input_encoding
    * output_encoding
    * filesystem_checks

    Please check mako.template:Template for more information.
    If no option is provided, pylons.config is used for default options.
    """
    tmpl_options = {}

    def __init__(self, use_default=True, **options):
        self.use_default=use_default
        if use_default:
            options = self._update_options(options)
        self.lookup = TemplateLookup(**options)
        # transfer options to template args, based on those available
        # in getargspec
        for kw in inspect.getargspec(Template.__init__)[0]:
            if kw in options:
                self.tmpl_options[kw] = options[kw]

    def render(self, string, namespace={}):
        if self.use_default:
            namespace = self._update_names(namespace)
        template = Template(string, lookup=self.lookup, **self.tmpl_options)
        return template.render(**namespace)

    def _update_options(self, custom_options):
        # update options with default
        options = {}
        d = pylons.config['buffet.template_options']
        for k, v in d.iteritems():
            if k.startswith('mako.'):
                options[k[5:]] = v
            elif k in ['directories', 'filesystem_checks', 'module_directory']:
                options[k] = v
        options.update(custom_options)
        if not options.get('directories'):
            options['directories'] = pylons.config['pylons.paths']['templates']
        return options

    # same as pylons.templating:Buffet
    def _update_names(self, ns):
        """Return a dict of Pylons vars and their respective objects updated
        with the ``ns`` dict."""
        d = dict(
            c=pylons.c._current_obj(),
            g=pylons.g._current_obj(),
            h=pylons.config.get('pylons.h') or pylons.h._current_obj(),
            render=render,
            request=pylons.request._current_obj(),
            translator=pylons.translator,
            ungettext=pylons.i18n.ungettext,
            _=pylons.i18n._,
            N_=pylons.i18n.N_
            )

        # If the session was overriden to be None, don't populate the session
        # var
        if pylons.config['pylons.environ_config'].get('session', True):
            d['session'] = pylons.session._current_obj()
        d.update(ns)
        return d


def render_string(string, namespace={}, use_default=True, **options):
    """ render string with mako engine """
    processor = MakoStringProcessor(**options)
    return processor.render(string, namespace=namespace)

__all__ = ['render_string']

posted by id:junya_hayashi