Writing Hexo filters

Hexo, the static blogging system that I use is very extensible and provides numerous hooks into generation pipeline.

While working on a Russian language blog that’s coming online soon, I had the opportunity to write a filter to render Cyrillic text in a different font than the rest of the body text.

Markup filter use case

I wanted to set the Cyrillic text apart both in color, typeface, and font weight. Although I could have extended Hexo using a new tag, I decided to use a filter so that after rendering HTML anywhere on the blog, items demarcated by double pipes || would be replaced by a new <span>.

I used an npm module to deploy the filter. You can find it on the npm and at its GitHub repo

Here’s the very short code for the filter itself:

hexo.extend.filter.register('after_render:html', function(str,data) {
var re = /(\|{2}?)((.|\n)+?)(\|{2}?)/gm;
var result = str.replace(re,'<span class="rsb">$2</span>');
return result;

The regex in the second line just identifies a block of text fenced by double pipes and replaces it with a span with the class that specifies the styling to be applied. In the future, I’d like to identify Cyrillic text with a regex and not have to use a fence at all.