Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to url encode in jekyll liquid?

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?

like image 230
Peterb Avatar asked Apr 12 '13 16:04

Peterb


People also ask

How do you encode a URL?

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is liquid Jekyll?

What is Liquid? Liquid is a templating language used in Jekyll to process your site's pages. In other words, it helps you make your HTML pages a bit more dynamic, for example adding logic or using content from elsewhere. This doesn't require any setup - we can just start using it.

Where is Jekyll?

Jekyll Island is a barrier island on Georgia's coast – midway between Jacksonville, Florida, and Savannah, Georgia.


1 Answers

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 }}">
like image 92
opello Avatar answered Oct 16 '22 04:10

opello