KLAC logo KLAC Word puzzle Available for

Insert common used data with a custom tag plugin in hexo blog engine

This website is build with hexo, a javascript based static web generator. It’s a powerful blog engine we extensively use and customize.

Among the features it provides, you can define custom data to use at your will. For instance, a list of common quotes or a list of pictures you put often in blog posts. You can define a list in the site data and reference it in each post you want to use.

In this website, we use a custom tag to access frequently used texts and manage them in a central place.
Here’s the step to achieve it.

Define the data

First of all, you need to define the data. In the folder _source/_data, create a file texts.yaml and write something like:

headline: This is a cool headline we reuse
description: This a long description we usually put in several blog post

In this example we use YAML format but you can use JSON if you feel more confident.

Define a custom tag

To insert the defined texts in a blog post you have to define a custom tag plugin. Head to the folder script and create a new file customTags.js.

We’re defining a custom tag named texts, so we can use it in any blog post.

hexo.extend.tag.register('texts', function (args) {
//get the text name we want to use
var name = args[0];
//get all the texts from the texts.yaml data file
var alltexts = hexo.locals.get('texts');

return alltexts[name];

Here texts tag name and texts data file have the same name. Don’t confuse one for the other. In the code above, the first one is the tag name we want to create, the second one is the filename we want to access.

Of course, you can do more complex stuff like returning html content or formatted text:

return '<b>' + alltexts[name] + '</b>';

Usage in a blog post

Now you can use the tag in a blog post, like this:

This is a blog post in markdown format

{% texts headline %}

The post content continues.

You can see how easily we referenced the headline text form the side data. Really painless.

Wrapping up

Site data is a powerful feature hexo provides. By using custom tags you can reference data as you wish.
The benefits are obvious:

  • You can insert common data very easily
  • No copy & paste mistakes
  • You can define complex snippets (i.e. html) you can reuse with no effort
  • Change data without the need to find and edit all posts it’s included
This website uses cookies to improve your experience