Hexo is an excellent static website generator for creating a blog.
Check out my post Top 5 Reasons to Blog with a Static Site Generator for
reasons you might want to use a static site generator.
For a complete introduction to setting up your blog with either Hexo or DocPad, check out
my Pluralsight course Build a Better Blog with a Static Site Generator.
In this post let’s look at how to extend your blog with a widget you can add via
a configuration file.
The default Hexo theme “Landscape” comes with a number of widgets like tagcloud, archive, and recent_posts.
If you take a look at the theme’s _config.yml file you’ll see the following:
As you can see under the widgets heading you can add or rearrange the widgets that will
appear in the sidebar.
As you can see in my blog I’ve added a few extra widgets like my most popular
posts list and my Twitter feed.
Let’s see what it takes to add the Twitter feed.
The theme folder structure of a Hexo blog is something like this:
As you can see under the layout folder is a “_widget” folder.
Each of the widgets available to the Landscape theme are stored in this directory
as *.ejs files.
We’ll take the archive.ejs as our example.
The first thing to notice is that has an if statement that makes sure we only
render the list if there are posts.
Next we see that the widget structure is defined by two divs and a header tag.
The outer div is of class “widget-wrap” and the inner div is of class “widget”.
Between the two divs is an H3 header of class “widget-title”.
If we follow this structure we can easily create our own widget.
We’ll just change the title and replace the
<%- list_archives() %> with the snippet we grab
from Twitter’s Create a User Widget page.
That gives us the following:
We’ll save that as twitterfeed.ejs in the layout/_widget directory.
Now we can add our new widget to the layout’s _config.yml (not the site’s):
That’s all there is to it.
In the next post I’ll create a widget that uses Hexo’s Data Files feature to
display items from a data file.
One last reminder to check out my Pluralsight course on
setting up your blog with either Hexo or DocPad at Build a Better Blog with a Static Site Generator.