Mix images with Markdown in a Flask app

2019-05-15 08:29发布

I am building a static site using Flask-FlatPages (and following up with Frozen-Flask).

Within my pages, I want to mix up the text with images. This would be the naive way to do this:

## Look at *this* image:
<img src="{{ url_for('static', filename='images/image.png') }}">
Hmm, it does **not** seem to load.

The {{ template tag }} is not being parsed, because FlatPages runs the page through markdown and not through Flask's templating system (if I am not mistaken).

How do I go about getting the correct image link?

Relevant code

#app.py
from flask import Flask, render_template
from flask_flatpages import FlatPages

app = Flask(__name__)
pages = FlatPages(app)

@app.route('/tip/<path:path>')
def tip_detail(path):
    tip = pages.get_or_404(path)
    template = tip.meta.get('template', 'tip_detail.html')
    return render_template(template, tip=tip)

and

#tip_detail.html
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<h1>{{ tip.meta.title }}</h1>
{{ tip }}
</body>
</html>

1条回答
Evening l夕情丶
2楼-- · 2019-05-15 08:52

Solved through a comment left by https://github.com/naringas at https://github.com/SimonSapin/Flask-FlatPages/pull/1

As it turns out Flask-FlatPages does not render Jinja template tags. It does however have an option to set a custom HTML renderer. Use that to first render the Jinja template before rendering the markdown.

#add these lines to app.py
def prerender_jinja(text):
    prerendered_body = render_template_string(Markup(text))
    return pygmented_markdown(prerendered_body)

app.config['FLATPAGES_HTML_RENDERER'] = prerender_jinja
查看更多
登录 后发表回答