Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Method to render string as template? #564

Closed
emehrkay opened this Issue · 4 comments

2 participants

Mark Henderson Ben Darnell
Mark Henderson

I was able to hack together a simple method, but I was wondering if what I did looks correct and if it would be useful to have something like this in web.ReqeustHandler?

I've added this to my main request handler class and it seems to work as expected

    def _template_string(self, string, **kwargs):
        template = web.template.Template(string, autoescape=None)
        args = dict(
            handler=self,
            request=self.request,
            current_user=self.current_user,
            locale=self.locale,
            _=self.locale.translate,
            static_url=self.static_url,
            xsrf_form_html=self.xsrf_form_html,
            reverse_url=self.reverse_url
        )
        args.update(**kwargs)
        args.update(self.ui)
        return template.generate(**args)

I use it with parsed markdown files that may contain template-based functionality like {{ modules.UI_MODULE() }}

The problems with this approach is that I am basically repeating code found in web.ReqeustHandler.render and I am not hooking into any of the cached named templates. Is there a better way to handle this?

Thanks

Mark Henderson

Sorry for the duplicate, I was trying to move it to the "feature" list

Ben Darnell
Owner

A refactoring along these lines (separating the creation of the template via the loader from the construction of arguments and actual rendering) seems reasonable.

As an alternate idea, you may want to try using a subclass of template.Loader that runs your templates through a markdown processor before generating code for them.

Ben Darnell
Owner

I've added get_template_namespace, which lets you do this in a few lines and avoid some of the mess:

def render_from_string(self, tmpl, **kwargs):
    namespace = self.get_template_namespace()
    namespace.update(kwargs)
    return Template(tmpl).generate(**namespace)
Mark Henderson

Awesome. You've always been very responsive, thanks!

Ben Darnell bdarnell closed this
Régis Gaidot rgaidot referenced this issue from a commit in rgaidot/tornado
Ben Darnell bdarnell Refactor template namespace from render_string to its own method.
This method may be overridden as an alternative to overriding render_string
and adding to kwargs, or may be used directly to render templates
without going through render_string (as when templates are constructed
directly; see tornadoweb#564)
5867170
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.