Created
January 31, 2019 05:02
-
-
Save johnfraney/69f8880325b4da221437125146b0ae2a to your computer and use it in GitHub Desktop.
Pygments-highlighted Wagtail StreamField code block
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 pygments import highlight | |
from pygments.formatters import HtmlFormatter | |
from pygments.lexers import get_lexer_by_name | |
from wagtail.core import blocks | |
from home.ayu_style import AyuStyle | |
class CodeBlock(blocks.StructBlock): | |
""" | |
Code Highlighting Block | |
""" | |
LANGUAGE_CHOICES = ( | |
('python', 'Python'), | |
('htmldjango', 'HTML + Django'), | |
('html', 'HTML'), | |
('css', 'CSS'), | |
('sass', 'SASS'), | |
('javascript', 'JavaScript'), | |
('typescript', 'TypeScript'), | |
('text', 'Plain Text'), | |
) | |
code = blocks.TextBlock() | |
language = blocks.ChoiceBlock(choices=LANGUAGE_CHOICES) | |
class Meta: | |
icon = 'code' | |
form_classname = 'code-block struct-block' | |
def render_basic(self, value, context=None): | |
src = value['code'].strip('\n') | |
lang = value['language'] | |
lexer = get_lexer_by_name(lang) | |
formatter = HtmlFormatter( | |
style=AyuStyle, | |
noclasses=True, | |
) | |
highlighted_code = highlight(src, lexer, formatter) | |
return mark_safe(highlighted_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment