From a9952b8f575b9ff709a63b574888a61184426277 Mon Sep 17 00:00:00 2001 From: vabene1111 Date: Fri, 28 Feb 2020 21:53:27 +0100 Subject: [PATCH] improved markdown rendering of tables and images --- cookbook/helper/mdx_attributes.py | 24 ++++++++++++++++++++++++ cookbook/templatetags/custom_tags.py | 11 ++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 cookbook/helper/mdx_attributes.py diff --git a/cookbook/helper/mdx_attributes.py b/cookbook/helper/mdx_attributes.py new file mode 100644 index 000000000..0d3cb1bb9 --- /dev/null +++ b/cookbook/helper/mdx_attributes.py @@ -0,0 +1,24 @@ +import markdown + +from markdown.treeprocessors import Treeprocessor + + +class StyleTreeprocessor(Treeprocessor): + + def run_processor(self, node): + for child in node: + if child.tag == "table": + child.set("class", "table table-bordered") + if child.tag == "img": + child.set("class", "img-fluid") + self.run_processor(child) + return node + + def run(self, root): + self.run_processor(root) + return root + + +class MarkdownFormatExtension(markdown.Extension): + def extendMarkdown(self, md, md_globals): + md.treeprocessors.register(StyleTreeprocessor(), 'StyleTreeprocessor', 10) diff --git a/cookbook/templatetags/custom_tags.py b/cookbook/templatetags/custom_tags.py index e762c59a9..199fcc85a 100644 --- a/cookbook/templatetags/custom_tags.py +++ b/cookbook/templatetags/custom_tags.py @@ -1,7 +1,9 @@ from django import template import markdown as md import bleach -from bleach_whitelist import markdown_tags, markdown_attrs +from bleach_whitelist import markdown_tags, markdown_attrs, all_styles, print_attrs + +from cookbook.helper.mdx_attributes import MarkdownFormatExtension register = template.Library() @@ -13,7 +15,6 @@ def get_class(value): @register.filter() def markdown(value): - return bleach.clean(md.markdown(value, extensions=['markdown.extensions.fenced_code']), markdown_tags, markdown_attrs) - - - + tags = markdown_tags + ['pre', 'table', 'td', 'tr', 'th', 'tbody', 'style', 'thead'] + test = md.markdown(value, extensions=['markdown.extensions.fenced_code', 'tables', MarkdownFormatExtension()]) + return bleach.clean(test, tags, print_attrs, markdown_attrs)