Forked from glombard/reference-markdown-metadata-from-jinja-template.py
Created
July 27, 2016 21:02
-
-
Save jfear/5bd2ab4bf9885292b1d7ae7650d58b12 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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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