Search code examples
pythonjinja2tornado

How to get template plain html without rendering with context vars in Jinja?


I have pack of templates, that import and extend parent templates, I'd like to get templates rendered with those imports and extends but without rendering context vars for jinja. Does jinja supports partial rendering with excluded or imported blocks? Is it possible not to render context vars and get template?


Solution

  • With Tornado, you can just read the templates and write them to the response. If you don't want to render them, don't use the render function.

    Example:

    class MyHandler(web.RequestHandler):
        def get(self):
            with open('/path/to/template.html') as f:
                self.write(f.read())
    

    Another solution:

    Jinja2 Environment class allows you to customize the brackets used for context variables. That means, you can set these brackets - {{ ... }} to some other characters, like - [[ ... ]], and Jinja2 will not render the old brackets. So, Jinja will not see these {{ }} as special characters and will output them just like any other character.

    This is a simple example:

    from jinja2 import Environment
    
    env = Environment(
        ... other usual options ...
        variable_start_string='[[',
        variable_end_string=']]'
    )
    

    And then use this env to render your template. All the variables with curly brackets - {{ ... }} won't be rendered and yet the other extended templates will also be included.