Last active
April 1, 2018 12:52
-
-
Save soar/2fdc7bcefd47d85be8c14f9febb89df8 to your computer and use it in GitHub Desktop.
Wagtail Markdown - simplest way
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
# django | |
from django import forms | |
from django.contrib.staticfiles.templatetags.staticfiles import static | |
from django.forms import Media, widgets | |
from django.utils.functional import cached_property | |
# wagtail | |
from wagtail.utils.widgets import WidgetWithScript | |
from wagtail.wagtailcore import blocks | |
# markdown | |
import markdown as MarkdownLibrary | |
class MarkdownBlock(blocks.TextBlock): | |
@cached_property | |
def field(self): | |
field_kwargs = { | |
'widget': MarkdownWidget(), | |
} | |
field_kwargs.update(self.field_options) | |
return forms.CharField(**field_kwargs) | |
class Meta: | |
icon = 'code' | |
template = 'blocks/markdown.html' | |
class MarkdownWidget(WidgetWithScript, widgets.Textarea): | |
def render_js_init(self, id_, name, value): | |
jsinit = """ | |
if (window.SimpleMDEInstances == null) {{ | |
window.SimpleMDEInstances = []; | |
}} | |
sm = new SimpleMDE({{ | |
element: document.getElementById("{id!s}"), | |
forceSync: true, | |
spellChecker: false | |
}}); | |
window.SimpleMDEInstances.push(sm); | |
""" | |
return jsinit.format(id=id_) | |
@property | |
def media(self): | |
js = [ | |
static('simplemde/js/simplemde.min.js'), | |
] | |
css = {'all': [ | |
static('simplemde/css/simplemde.min.css'), | |
]} | |
return Media(js=js, css=css) |
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
# django | |
from django import template | |
from django.utils.safestring import mark_safe | |
# markdown | |
import markdown as MarkdownLibrary | |
register = template.Library() | |
@register.filter(name='markdown') | |
def markdown_filter(value): | |
return mark_safe(MarkdownLibrary.markdown( | |
value, | |
output_format='html5', | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SimpleMDE required - it can be downloaded here: https://simplemde.com/