What will you learn in this post?
This post introduces how to achieve searching tags with Jekyll, without using a Jekyll Plugin.
Since Jekyll is a static Website generator, which means the pages are already there before you request, it is hardly possible to for Liquid to get the query string in URL. However, we can use some tricks to make it looks like so.
The basic idea is to display all posts grouped by tags, and then use CSS display: none
for all except posts with the searching tag. We can get the searching tag in URL query string using JavaScript.
#Display Posts Grouped by Tags
1. Create a page called tags.html
.
Tags can be then searched like http://.../tags/?tag=css
.
2. Get all the tag names in site.tags
.
You’d better use -
instead of space in your tag names. Otherwise, if you have a tag named Hello World
, then site.tags
contains Hello
and World
. To avoid this, use Hello-World
as tag name instead.
3. For each tag, list all the posts with that tag name.
Here we create a <div></div>
for each tag with id
and class
so that it can be manipulated more easily later.
4. Hide all those tag-posts
.
Use CSS to set display: none;
to .tag-posts
.
5. Get query string using JavaScript.
6. Show posts with the searching tag.
7. Add links to tags.
Now, you can search tags like /tags?tag=Jekyll
.
#Conclusion
Full code is available at GitHub.
This is an easy way to achieve searching tag for static Jekyll. One disadvantage is that a full list of all posts grouped by tags needs to be loaded whenever a tag is searched. This is not so good when blog posts become large enough. However, this is by far the simplest implementation I can think of.
#Reference
-
StackOverflow: An easy way to support tags in a jekyll blog
-
StackOverflow: How can I get query string values in JavaScript?