[Flask] Recursively expanding template content

Skip Montanaro skip.montanaro at gmail.com
Wed Apr 26 15:29:53 EDT 2017


This will probably sound weird, but I have an index.html template
which basically looks like

...
<body>
  {{ content }}
</body>
...

The content comes from a Markdown file generated by

import markdown
from flask import Markup

...

content = Markup(markdown.markdown(raw))

where "raw" is the raw content of the Markdown file.

I'd like to embed some Jinja2 references in the Markdown file and have
them automagically processed as if they appeared in the index.html
template. In particular, I'd like to call render_template with the
netloc:

content = Markup(markdown.markdown(raw))
netloc = urlparse.urlparse(request.url).netloc
return render_template("index.html", **locals())

Currently, I fudge by just replace()ing the "{{ netloc }}" references:

content = Markup(markdown.markdown(raw)).replace("{{ netloc }}", netloc)

That works, but seems crude. I tried explicitly calling
Jinja2.Template().render():

content = Markup(markdown.markdown(raw))
netloc = urlparse.urlparse(request.url).netloc
template = jinja2.Template(content)
content = template.render(netloc=netloc)
return render_template("index.html", **locals())

That kinda worked, but left me with a bunch of escaped HTML entities.
My guess is that render_template doesn't like "<" and such in its
input strings.

I suspect there is an elegant solution to this, but as I am not wise
in the ways of Flask, Jinja, or markdown, it's certainly not jumping
out at me. Pointers (especially to documentation I've missed *) would
be appreciated.

Skip Montanaro

(*) Prefer doc links rather than StackOverflow links, though they will
do in a pinch.


More information about the Flask mailing list