Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save glombard/7554134 to your computer and use it in GitHub Desktop.
Save glombard/7554134 to your computer and use it in GitHub Desktop.
How to use Markdown as a filter in a Jinja2 template, and then extract the Markdown Meta property directly from the template. Assuming you want to use the Meta-data value before rendering the converted Markdown content (e.g. in the html head), the trick is to render the markdown first, save it to a variable (html_content in this example) using a…
from pprint import pprint
import jinja2
import markdown
HTML_TEMPLATE = """{% macro get_html() %}
{{ content | markdown }}
{% endmacro %}
{% set html_content = get_html() %}
Title from Markdown meta-data: {{ get_title() }}
{{ html_content }}
"""
MARKDOWN_WITH_METADATA = """Title: Hello world!
Header:
-------
*Markdown content*
"""
md = markdown.Markdown(extensions=['meta'])
env = jinja2.Environment()
env.filters['markdown'] = lambda text: jinja2.Markup(md.convert(text))
env.globals['get_title'] = lambda: md.Meta['title'][0]
env.trim_blocks = True
env.lstrip_blocks = True
print(env.from_string(HTML_TEMPLATE).render(content=MARKDOWN_WITH_METADATA))
print('title meta-data is retrieved from the content:')
pprint(md.Meta['title'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment