-
-
Save iho/0c49c0f739403925f78b to your computer and use it in GitHub Desktop.
Code and Markdown blocks for Wagtail 1.0 StreamField
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
from django.utils.safestring import mark_safe | |
from markdown import markdown | |
from pygments import highlight | |
from pygments.formatters import get_formatter_by_name | |
from pygments.lexers import get_lexer_by_name | |
from wagtail.wagtailcore import blocks | |
class CodeBlock(blocks.StructBlock): | |
""" | |
Code Highlighting Block | |
""" | |
LANGUAGE_CHOICES = ( | |
('python', 'Python'), | |
('bash', 'Bash/Shell'), | |
('html', 'HTML'), | |
('css', 'CSS'), | |
('scss', 'SCSS'), | |
) | |
language = blocks.ChoiceBlock(choices=LANGUAGE_CHOICES) | |
code = blocks.TextBlock() | |
class Meta: | |
icon = 'code' | |
def render(self, value): | |
src = value['code'].strip('\n') | |
lang = value['language'] | |
lexer = get_lexer_by_name(lang) | |
formatter = get_formatter_by_name( | |
'html', | |
linenos=None, | |
cssclass='codehilite', | |
style='default', | |
noclasses=False, | |
) | |
return mark_safe(highlight(src, lexer, formatter)) | |
class MarkDownBlock(blocks.TextBlock): | |
""" MarkDown Block """ | |
class Meta: | |
icon = 'code' | |
def render_basic(self, value): | |
md = markdown( | |
value, | |
[ | |
'markdown.extensions.fenced_code', | |
'codehilite', | |
], | |
) | |
return mark_safe(md) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment