Wagtail is an awesome CMS built on top of Django. I have been using Django for sometime now and Wagtail has become my go-to CMS. It is very developer friendly, as well as a delight for content editors.
One standout feature of Wagtail is the StreamField - a very flexible way to create and modify content. You can read about them here . I use this a lot and so I though I would share a simple example of a Block that can be used inside a StreamField for rendering sections of 'code', just like I am in this blog post.
"""
this is in my flexi_fields.models.py
"""
from wagtail.wagtailcore import blocks
CODE_CHOICES = [
('python', 'python'),
('javascript', 'javascript'),
('css', 'css'),
('markup', 'markup')
]
class CodeBlock(blocks.StructBlock):
language = blocks.ChoiceBlock(choices=CODE_CHOICES, default="python")
text = blocks.TextBlock()
class Meta:
template = "flexi_fields/sections/code_section.html"
icon = "openquote"
label = "Code Block"
The CodeBlock class (above) can be imported into blocks.py to become part of a StreamBlock, which in turn can be used as a 'body' field of, say, a BlogPage - like this one!
"""
this is my flexi_fields.blocks.py
"""
from flexi_fields.models import CodeBlock
class MultiSectionBlock(blocks.StreamBlock):
# your other....
# blocks go here...
code_block = CodeBlock()
class Meta:
icon = "placeholder"
template = ""
label = "Multi Section"
"""
This is in my blog app's models.py
"""
from wagtail.wagtailcore.models import Page
from flexi_fields.blocks import MultiSectionBlock
from wagtail.wagtailcore.fields import StreamField
class BlogPage(Page):
body = StreamField(MultiSectionBlock(), null=True, blank=True)
# the rest of your BlogPage class here...
<!-- This is in my template -->
<!-- flexi_fields/sections/code_section.html -->
{% load wagtailcore_tags %}
<section>
{# do not indent the "{{ self.text.}}" code below, or else 'prism' will add that indentation to the first line outputted :-) #}
<pre><code class="language-{{ self.language }}">
{{ self.text }}
</code></pre>
</section>
I use prismjs for the client-side syntax highlighting and I highly recommend it - it is very easy to use.
Go ahead and include prismjs into your html like the next two snippets.
<link rel="stylesheet" type="text/css" href="{% static 'css/prism.css' %}">
<script src="{% static 'js/prism.js' %}"></script>