My First Stab at a Useful Liquid Tag

I’ve experimented with a number of ways to display code on this site. I have come to prefer using Google Code Prettify because of its simplicity and elegance. Until recently, I would “drop down” into HTML from writing my note in Markdown, something like this:

Some markdown text...
<pre class="prettify"><code>IEnumerable&gt;string&lt; GetStrings()
    foreach (string str in this.strings)
        yield return str;
Some more markdown text...

Note that I had to put the code right after the opening <pre><code>—it would preserve the line break if I didn’t. Also, if the code contained any characters special to HTML, like angle brackets, as my example above does, and as many languages do, I would have to escape those characters myself. But last night, dabbling in Liquid, I produced the {% code %} tag:

require 'cgi'

class CodeBlock < Liquid::Block
  def initialize(name, markup, tokens)

  def render(context)
    output = super
    source = "<pre class=\"prettyprint highlight\"><code>"
    source += CGI.escapeHTML(output.strip)
    source += "</code></pre>"

Liquid::Template.register_tag('code', CodeBlock)

This is my first stab at a Liquid tag. I want to add the ability to pass certain parameters to the tag, mostly to support the parameters that Google Code Prettify blocks can support.

blog comments powered by Disqus