HomeBlog
Replace-Last Filter for Jekyll Liquid - 羡辙杂俎
2014.08.04 21:54:08
Replace-Last Filter for Jekyll Liquid

What will you learn in this post?

There are only replace and replace-last filter in Liquid gramma. So how can we replace the last character in Jekyll? This post introduces an ad-hoc method to do this, as well as how to make a View Source on GitHub feature.

Why did I need this filter?

I was making a View Source in GitHub feature for my blog and needed to replace / with - in {{ page.url}}, which is /2014/07/15/jekyll/related/posts/without/plugin/, so as to generate a link like https://raw.githubusercontent.com/Ovilia/blog/gh-pages/_posts/2014-07-15-jekyll-related-posts-without-plugin.md.

As we can see, https://raw.githubusercontent.com/Ovilia/blog/gh-pages/_posts/ and .md remains always the same. So we just need to get 2014-07-15-jekyll-related-posts-without-plugin from /2014/07/15/jekyll/related/posts/without/plugin/, which seems to be a piece of cake, right?

No! Not with Liquid.

replace and remove-first

Good Resource of Liquid Gramma

Standard Filters - Liquid for Designers

We can use replace to replace / with -. But we want to get rid of the first and last / in /2014/07/15/jekyll/related/posts/without/plugin/. The first / can be easily removed using remove-first, but how about the last one?

Apparently, there’s no Liquid filter we can use. But you have to do something to stay alive with Liquid. :smirk:

append?!

As traditional Chinese philosophy told us, One must first give, when he wants to get. When we can’t find any solution to remove, why not consider append?

One must first open, when he wants to close.
One must first strengthen it, when he wants to weaken something.
One must first embrace, when he wants to abolish.
One must first give, when he wants to get.

from Tao Te Ching

We first append a character which is considered never to be in the post URL. For example, we choose @ here and put our trust on it that it will never betray us. :joy:

Append @ to the end of the string and remove -@ helps to remove the last - in the original string.

The complete code is:

博文对你有帮助吗?如果有的话,要不要送我一本书呢?:heart_eyes:

微信公众号“羡辙部落格”(xianzheblog)提供本站优质非技术类博文推送。

Creative Commons License
Every blog post in this site by Wenli Zhang is licensed under a CC 3.0 License, based on a work at Github. You can see the source code of this blog site at github.com/Ovilia/blog.

Comments

comments powered by Disqus