Skip to content

Instantly share code, notes, and snippets.

@quodos
Last active April 16, 2018 08:06
Show Gist options
  • Save quodos/fff29dc65dc831197f184dcf10c5fb0c to your computer and use it in GitHub Desktop.
Save quodos/fff29dc65dc831197f184dcf10c5fb0c to your computer and use it in GitHub Desktop.
Freemarker function that generates a URL friendly "slug" from a given string
<#-- The strSlug function generates a URL friendly "slug" from the given string -->
<#-- TODO: convert non-ASCII chars to ASCII chars -->
<#-- Copyright (c) 2018 Thomas Wilhelm <thomas.p.wilhelm@gmail.com> -->
<#function strSlug title seperator="-" idSafe=true>
<#local flipped = "_" />
<#if seperator == "_">
<#local flipped = "-" />
</#if>
<#local string = title?replace("[" + flipped + "]+", seperator, "r") />
<#local string = string?lower_case />
<#local string = string?replace("[ \t\n\x0B\f\r]+", seperator, "r") />
<#local string = string?replace("[^" + seperator + "a-z0-9]+", seperator, "r") />
<#if idSafe == true>
<#local string = string?replace("^" + seperator, "", "r") />
</#if>
<#local string = string?replace("[" + seperator + "]+", seperator, "r") />
<#return string />
</#function>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment