Python Thumbnail
June 14, 2022, 7:15 p.m.

Some Random Blocks

Some random blocks I made for this site.

Code Block

This is the block class for showing syntax highlighted code. It takes a language as a freeform text that gets interpreted by the Pygments package to determine the highlighting required. For example, I've used python and django for the blocks in this post. The accompanying template uses the safe filter to make sure the HTML that Pygments provide is not escaped.

codeblock.py
    
class CodeBlock(blocks.StructBlock):

    filename = PreCharBlock(required=False, max_length=255)
    code = blocks.TextBlock()
    language = blocks.CharBlock(required=False, max_length=128, help_text="Syntax highlighting required")

    class Meta:
        template = "blocks/code.html"
        icon = "code"

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context)
        lexer = lexers.get_lexer_by_name(context["value"]["language"])
        style = get_style_by_name("native")
        formatter = HtmlFormatter(full=False, style=style)
        context["formatted"] = highlight(context["value"]["code"], lexer, formatter)
        return context
code.html
    
{% load wagtailcore_tags %}
<div class="highlight">
{% if value.filename %}
<div class="ui basic segment top attached tiny">{{ value.filename }}</div>
{% endif %}
<pre class="ui basic segment attached">
    {{ formatted | safe }}
</pre>
</div>

Image Block

The Image block class is used on pages to display an image with a caption and optional source. It also allows the image to be floated left or right. It kinda needs to be extended to allow the user to give the size of the image as well.

imageblock.py
    
class ImageBlock(blocks.StructBlock):
    float_image = blocks.ChoiceBlock(
        [
            ("", "No"),
            ("floated left", "Floated Left"),
            ("floated right", "Floated Right"),
        ],
        required=False,
    )
    size = blocks.ChoiceBlock(
        [
            ("", "Default"),
            ("small", "Small"),
            ("medium", "Medium"),
            ("large", "Large"),
        ],
        required=False,
    )
    image = ImageChooserBlock(required=True)
    caption = blocks.TextBlock(required=False)
    source = blocks.TextBlock(required=False)
    source_link = blocks.URLBlock(required=False)

    class Meta:
        template = "blocks/image.html"
        icon = "image"
        value_class = ImageStructValue
image.html
    
{% load wagtailimages_tags %}
<div class="ui image spaced image-block {{ value.float_image }} {{ value.size }}">
    {% image value.image original as the_image %}
    <a href="{{ the_image.url }}" data-caption="{{ value.source_alt | safe }}" target="_blank">
        {% image value.image fill-320x320-c100 alt=value.source_alt  %}
    </a>
    <div class="ui image-source">{{value.source_alt | safe }}</div>
</div>