Add mode parameter to slugify Liquid filter

This commit is contained in:
nitoyon 2014-09-14 02:38:37 +09:00
parent 25d77cb05a
commit 46e76bde3f
2 changed files with 47 additions and 16 deletions

View File

@ -50,12 +50,12 @@ module Jekyll
# Slugify a filename or title.
#
# input - The filename or title to slugify.
# mode - how string is slugified
#
# Returns the given filename or title as a lowercase String, with every
# sequence of spaces and non-alphanumeric characters replaced with a
# hyphen.
def slugify(input)
Utils.slugify(input)
# Returns the given filename or title as a lowercase URL String.
# See Utils.slugify for more detail.
def slugify(input, mode=nil)
Utils.slugify(input, mode)
end
# Format a date in short format e.g. "27 Jan 2011".

View File

@ -104,19 +104,50 @@ module Jekyll
# Slugify a filename or title.
#
# name - the filename or title to slugify
# string - the filename or title to slugify
# mode - how string is slugified
#
# Returns the given filename or title in lowercase, with every
# sequence of spaces and non-alphanumeric characters replaced with a
# hyphen.
def slugify(string)
unless string.nil?
# Replace each non-alphanumeric character sequence with a hyphen
slug = string.gsub(/[^a-z0-9]+/i, '-')
# Remove leading/trailing hyphen
slug.gsub!(/^\-|\-$/i, '')
slug.downcase
# When mode is "none", return the given string in lowercase.
#
# When mode is "raw", return the given string in lowercase,
# with every sequence of spaces characters replaced with a hyphen.
#
# When mode is "default" or nil, non-alphabetic characters are
# replaced with a hyphen too.
#
# When mode is "pretty", some non-alphabetic characters (._~!$&'()+,;=@)
# are not replaced with hyphen.
#
# Examples:
# slugify("The _config.yml file")
# # => "the-config-yml-file"
#
# slugify("The _config.yml file", "pretty")
# # => "the-_config.yml-file"
#
# Returns the slugified string.
def slugify(string, mode=nil)
mode ||= 'default'
return nil if string.nil?
# Replace each character sequence with a hyphen
re = case mode
when 'raw'
Regexp.new('\\s+')
when 'default'
Regexp.new('[^a-zA-Z0-9]+')
when 'pretty'
# "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL
# and is allowed in both extN and NTFS.
Regexp.new("[^a-zA-Z0-9._~!$&'()+,;=@]+")
else
return string.downcase
end
slug = string.gsub(re, '-')
# Remove leading/trailing hyphen
slug.gsub!(/^\-|\-$/i, '')
slug.downcase
end
end