Method to render string as template? #564

emehrkay opened this Issue Jul 17, 2012 · 4 comments

2 participants


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(
        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?



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

tornadoweb member

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.

tornadoweb member

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()
    return Template(tmpl).generate(**namespace)

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

@bdarnell bdarnell closed this Aug 27, 2012
@rgaidot rgaidot pushed a commit to rgaidot/tornado that referenced this issue Nov 17, 2013
@bdarnell 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment