Mix images with Markdown in a Flask app

核能气质少年 提交于 2019-12-07 16:55:31

问题


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:


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


来源:https://stackoverflow.com/questions/21576520/mix-images-with-markdown-in-a-flask-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!