How to url encode in jekyll liquid?
jekyll, liquid, ruby
Solution
Using `cgi_escape` doesn't work correctly for categories with spaces. Links were generated as `/category/the+category` instead of `/category/the%20category`.
The solution I ended up using was from this blog post:
# _plugins/url_encode.rb
require 'liquid'
require 'uri'
# Percent encoding for URI conforming to RFC 3986.
# Ref: http://tools.ietf.org/html/rfc3986#page-12
module URLEncoding
def url_encode(url)
return URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end
end
Liquid::Template.register_filter(URLEncoding)
A plus is a literal plus anywhere but in the query portion of the URL, where it represents a space. Good URL encoding reference (archive.org mirror).
This can then be used in a layout or anywhere else:
<a href="{{ site.category_dir }}/{{ category | url_encode }}">
Problem
I have problem that categories are not url encoded when I use german words with Umlauts (e.g. ä, ü). I tried the cgi_escape that Liquid seems to offer, but success with the following code: ``` <strong>Kategorien</strong><br/> {% for category in site.categories do %} <small><a href="/categories/{{ category[0] | cgi_escape }}">{{ category[0] }} </a><br/> </small> {% endfor %} ``` Can anyone help?