Skip to content

Instantly share code, notes, and snippets.

@mikefromit
Last active August 29, 2021 11:21
Show Gist options
  • Save mikefromit/5a6fdfecc9310712f15a872df9f41f03 to your computer and use it in GitHub Desktop.
Save mikefromit/5a6fdfecc9310712f15a872df9f41f03 to your computer and use it in GitHub Desktop.
Markdown filter for jinja2

markdown.py

@environmentfilter
def markdown(env, value):
    """
    Markdown filter with support for extensions.
    """
    try:
        import markdown as md
    except ImportError:
        log.error(u"Cannot load the markdown library.")
        raise TemplateError(u"Cannot load the markdown library")
    output = value
    # insert custom markdown extensions here
    extensions = ['markdown.extensions.meta',
                  'markdown.extensions.headerid',
                  'markdown.extensions.attr_list',
                  'markdown.extensions.toc',
                  'markdown.extensions.def_list']

    d = dict()
    d['extensions'] = list()
    d['extensions'].extend(extensions)

    marked = md.Markdown(**d)

    return marked.convert(output)


class Markdown(Extension):
    """
    A wrapper around the markdown filter for syntactic sugar.
    """
    tags = set(['markdown'])

    def parse(self, parser):
        """
        Parses the statements and defers to the callback
        for markdown processing.
        """
        lineno = next(parser.stream).lineno
        body = parser.parse_statements(['name:endmarkdown'], drop_needle=True)

        return nodes.CallBlock(
            self.call_method('_render_markdown'),
            [], [], body).set_lineno(lineno)

    def _render_markdown(self, caller=None):
        """
        Calls the markdown filter to transform the output.
        """
        if not caller:
            return ''
        output = caller().strip()
        return markdown(self.environment, output)

The initialization on your flask app

from .ext.jinja2.markdown import Markdown, markdown

app = Flask(package_name,
                instance_relative_config=True,
                template_folder='templates')
app.config.from_pyfile('config.py', silent=True)

if settings_override is not None:
    app.config.from_object(settings_override)

# register jinja2 extensions and filters

jinja_extensions = [
    'jinja2.ext.do',
    'jinja2.ext.loopcontrols',
    'jinja2.ext.with_',
    Markdown
]

app.jinja_options = app.jinja_options.copy()
app.jinja_options['extensions'].extend(jinja_extensions)
app.jinja_env.filters['markdown'] = markdown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment