If you have some data you’d like to load from a file and use to generate a widget
for your Hexo blog, Data Files are just the ticket.
Or rather they would be if they worked.
Scratch that… they actually work just fine, but the documentation is kind of wrong (as of
the time I’m writing this at least).
The idea is that you can create either a YAML or JSON file and store it in a directory
called _data in your source directory, then spin through all the items in it in code.
Here’s what the docs show:
So let’s make a widget that uses a Data File successfully.
That’s exactly how I implemented my blog’s Popular Posts widget.
The first thing we need is a file with data.
Since I have some characters that don’t play well with YAML, I have to wrap everything
up in quotes.
My current file (popularposts.yml) looks like this:
If you’ve read my last post Creating a Hexo Widget,
then you know that the base of a widget is this:
So we just need to adapt that and replace “Your widget content here” with code to spin through our list and spit out links.
Here’s what my popularposts.ejs looks like:
As you can see the concept is the same, just the syntax is different.
On the first line you can see how to reference your data.
site.data.popularposts where “popularposts.yml” is the file name.
On line 6 you can see how to implement a for loop over the data items, and
on line 7 you can see how to reference both the keys and values.
It’s not really difficult and it works well, so it’s a shame the docs are confusing
If you’d like a complete walkthrough of how to set up your blog with either Hexo
or DocPad, be sure to check out my Pluralsight course
Build a Better Blog with a Static Site Generator.
I’ll walk you through everything from installing Hexo to prettying up the Landscape theme
to adding comments with Disqus and deploying with Git.