简体   繁体   中英

How to url encode in jekyll liquid?

I have problem that categories are not url encoded when I use german words with Umlauts (eg ä, ü). 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?

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 }}">

@Peterb, have you upgraded to the latest version of Jekyll? The current 1.0x version supports UTF-8 and handles URLs like this much better.

You can install the latest version by running this from your Terminal command line:

$ [sudo] gem install jekyll --pre

This GitHub Issue post will shed more light on the issue: https://github.com/mojombo/jekyll/issues/960

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM