Skip to content

Commit

Permalink
Merge pull request #13 from moggers87/8-markdown-filters
Browse files Browse the repository at this point in the history
Template filters

Fixes #8
  • Loading branch information
moggers87 committed Jul 1, 2018
2 parents b30fc4c + a5cf83a commit 2905c94
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
21 changes: 20 additions & 1 deletion exhibition/filters/jinja2.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@
filter: exhibition.filters.jinja2
"""

from jinja2 import Environment, FileSystemLoader
from jinja2 import Environment, FileSystemLoader, contextfilter
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension
from jinja2.nodes import CallBlock, ContextReference, Const
from typogrify.templatetags import jinja_filters as typogrify_filters
from markdown import markdown as md_func


EXTENDS_TEMPLATE_TEMPLATE = """{%% extends "%s" %%}
Expand All @@ -46,6 +48,20 @@

NODE_TMPL_VAR = "node"

DEFAULT_MD_KWARGS = {
"output_format": "html5",
}


@contextfilter
def markdown(ctx, text):
kwargs = DEFAULT_MD_KWARGS.copy()
node = ctx[NODE_TMPL_VAR]

kwargs.update(node.meta.get("markdown_config", {}))

return md_func(text, **kwargs)


class RaiseError(Extension):
"""
Expand Down Expand Up @@ -120,6 +136,9 @@ def content_filter(node, content):
extensions=[RaiseError, Mark],
autoescape=True,
)
env.filters["markdown"] = markdown
typogrify_filters.register(env)

parts = []

if node.meta.get("extends"):
Expand Down
28 changes: 26 additions & 2 deletions exhibition/tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,21 @@
Hello
{% endmark %}
Bye
"""
""".strip()

MD_TEMPLATE = """
{% filter markdown %}
## Hello
This is *text*
{% endfilter %}
""".strip()

TYPOG_TEMPLATE = """
{% filter typogrify %}
Hello -- how are you?
{% endfilter %}
""".strip()


class Jinja2TestCase(TestCase):
Expand Down Expand Up @@ -139,4 +153,14 @@ def test_mark_extension(self):
with pathlib.Path(deploy_path, "blog.html").open("r") as f:
content = f.read()

self.assertEqual(content, "\n\nHello\n\nBye")
self.assertEqual(content, "\nHello\n\nBye")

def test_markdown_filter(self):
node = Node(mock.Mock(), None, meta={"templates": []})
result = jinja_filter(node, MD_TEMPLATE)
self.assertEqual(result, "<h2>Hello</h2>\n<p>This is <em>text</em></p>")

def test_typogrify_filter(self):
node = Node(mock.Mock(), None, meta={"templates": []})
result = jinja_filter(node, TYPOG_TEMPLATE)
self.assertEqual(result, "\nHello &#8212; how are&nbsp;you?\n")
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
install_requires=[
"click",
"jinja2",
"markdown",
"ruamel.yaml",
"typogrify",
],
entry_points={
"console_scripts": [
Expand Down

0 comments on commit 2905c94

Please sign in to comment.