Skip to content

Instantly share code, notes, and snippets.

@soar soar/markdownblock.py
Last active Apr 1, 2018

Embed
What would you like to do?
Wagtail Markdown - simplest way
# 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)
# 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',
))
@soar

This comment has been minimized.

Copy link
Owner Author

commented Jun 9, 2016

SimpleMDE required - it can be downloaded here: https://simplemde.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.