Lukas Z's Private Blog

(mostly about programming)

Custom Wrapper-DIV in Octopress

After writing the last post I wanted to add a div that would wrap the email I pasted so I can add some custom style to it. But if I just surrounded the markdown that made up the email with div-tags, then markdown would no longer render the contents and everything inside the div would be displayed as plaintext.

So enter Liquid::Block. The plan was to wrap the source that I wanted wrapped in a div using a liquid-tag.

I dug trough the source of Tobias Lütke’s Liquid to understand how to do it, but I obviously have some more digging to do. However, it’s probably quite clever. Basically, liquid allows to write secure markup that doesn’t eval anything. Everything that inherits from Liquid classes seem to have all methods unset which allows only calls to specifically defined methods.

Well, anyway. I’m sure there’s much more to it, but here’s my tiny little Octopress-plugin that just wraps the contents in a div. Since I’m using markdown, it will only work with markdown.

module Jekyll
        class CustomDivBlock < Liquid::Block
                def initialize(name, params, tokens)
                        @klass = params.strip

                def render(context)
                        output = super ).to_html
                        "<div class='#{@klass}'>#{output}</div><div class='after_#{@klass}'></div>"

Liquid::Template.register_tag('customdiv', Jekyll::CustomDivBlock)

It can be now used like this is an Octopress source-file (the quote is from William Gibsons “Neuromancer”, btw.):

{% customdiv paper %}
“All the speed he took, all the turns he'd taken and the corners he'd cut in Night City, and still he'd see the matrix in his sleep, bright lattices of logic unfolding across that colorless void...” 
{% endcustomdiv %}

Here’s the result of the above:

“All the speed he took, all the turns he’d taken and the corners he’d cut in Night City, and still he’d see the matrix in his sleep, bright lattices of logic unfolding across that colorless void…”

It’s probably the “Hello World” of Octopress-plugins, but hey. Next time I have some time off, I’ll just read some more and revise / awesomify this plugin.

P.S.: You can follow me on Twitter.