Answer a question

Basically, I want to create editor, where you can edit part of the page using jinja2 syntax. In editor, if you press Preview, I want to be able see rendered template included into page, but with all variables and custom filters which page itself has. My current code is:

Python

from flask import render_template
from jinja2 import Template

# (... route logic here ...)
return render_template('preview.html',
   title='Some title',
   preview=Template("This is {{ title }}.")

Jinja2

{{ title }}
{{ preview.render() }}

But output is:

Some title
This is .

Is it possible to render my template from string with page context that output will be like this?

Some title
This is Some title.

Answers

Update

If you want to render a sub template and inherit the context from the parent template, then you can use include, which is usually used with a template path (e.g., {% include 'template.html' %} but also works with a Template object:

{{ title }}
{% include preview %}

Original Answer

You need to pass the context to preview.render() in the first template. Try this:

{{ title }}
{{ preview.render(title=title) }}
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐