This article is pretty much useless now. Statamic now uses Markdown Extra which lets you use Fenced Code Blocks.
Now all you have to do is surround your code with
~~~. You can even add classes.
You can read more about this here.
Markdown is nice
Statamic uses Markdown for its content parser. This is great, because it’s so easy to add code blocks. All you need to do is indent the code with a tab (or 4 spaces). You don’t need to worry about encoding the opening and closing tag brackets into their entities. Then, Markdown will wrap the code in
<code> tags. Great.
But there’s a problem
<pre> tag is out of your control, you can’t add any classes or attributes to it. Not really a problem until you add a syntax highlighter to your project. In my case, I wanted to use Lea Verou’s Prism — mainly because it’s tiny, only 1.5kb — and also because it’s awesome.
The issue here is that Prism looks for the language of the class of the tag… which we can’t add ourselves.
So here’s the solution
Another reason Markdown is great is because you can use HTML throughout it with no issue.
Knowing these two things, we can just wrap our code in a
Something like this:
Although, there’s another problem with this. Markdown won’t be parsed within an HTML block. So the code you enter will be rendered as if it were plain old code in your source.
To get your code block to be interpreted as markdown again, all you need to do is add
markdown="1" to your
Which will render this:
var message = "these two lines will now be a code block. ahh"; console.log(message);
Using this technique means you have an extra non-semantic wrapper around each code block. Not a huge deal, but for those code purists there, this may put you off a little.
I’d love to hear a better way to do this.