Skip to content

Instantly share code, notes, and snippets.

@xavianaxw
Last active July 29, 2023 18:50
Show Gist options
  • Save xavianaxw/b683fa0967d36faf619530eb3ed59c1f to your computer and use it in GitHub Desktop.
Save xavianaxw/b683fa0967d36faf619530eb3ed59c1f to your computer and use it in GitHub Desktop.
Hubspot | slugify() | Converting text into slug for Hubspot
{# Helpers: slugify #}
{# Returns the slug version of a string #}
{# Parameters #}
{# string | String to convert into a slug | Required #}
{# How to import this macro to my module #}
{# {% from '[folder]/slugify.html' import slugify %} #}
{# How to use this macro #}
{# {{ slugify('Give me slug') }} #}
{%- macro slugify(text) -%}
{%- set output = text %}
{%- set output = output | string | lower -%}
{%- set output = output | regex_replace("[\t\n\f\r ]", "-") -%} {# replace spaces with - #}
{%- set output = output | regex_replace("[^0-9A-Za-z_-]", "") -%} {# remove all non-word characters #}
{%- set output = output | regex_replace("-+", "-") -%} {# replace multiple - with single - #}
{%- set output = output | regex_replace("^[-]", "") -%} {# trim - from start of text #}
{%- set output = output | regex_replace("[-]$", "") -%} {# trim - from end of text #}
{{- output -}}
{%- endmacro -%}
@xavianaxw
Copy link
Author

Remember to remove linebreaks when setting up on Hubspot. Else it will cause a linebreak when including them into html.

{%- macro slugify(text) -%}{%- set output = text -%}{%- set output = output | string | lower -%}{%- set output = output | regex_replace("[\t\n\f\r ]", "-") -%}{%- set output = output | regex_replace("[^0-9A-Za-z_-]", "") -%}{%- set output = output | regex_replace("-+", "-") -%}{%- set output = output | regex_replace("^[-]", "") -%}{%- set output = output | regex_replace("[-]$", "") -%}{{- output|trim -}}{%- endmacro -%}

@reatlat
Copy link

reatlat commented Jul 29, 2023

@xavianaxw sometimes you may use slugify macros for custom text fields, where content managers may pass html tags like <br/> or do something with span wrappers, and to avoid issues, I think will be nice to have safe and striptags filters
something like this:

{%- set output = output | string | lower | safe | striptags -%}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment