How to create slug-formatted strings from text in HubL templates

I’m working on a HubSpot template and need help with transforming regular text into URL-friendly slug format using HubL filters. Basically I want to take something like My Sample Text and turn it into my-sample-text for use as CSS class names in my template modules.

I’ve been searching through the HubL documentation but can’t find a built-in filter that does this conversion automatically. Since HubL runs on Python, I’m wondering if there are any Python string methods that work within HubL templates that could help with this.

Has anyone found a good way to handle this text transformation in HubSpot templates? Any suggestions would be really helpful.

There’s a simple way to do this with chained HubL filters. Use {{ text_variable | lower | regex_replace('[^a-z0-9\s]', '') | replace(' ', '-') }} - it strips special characters first, then converts spaces to hyphens. I’ve used this tons of times in custom modules when I need dynamic CSS classes from content fields. The regex kills problematic stuff like apostrophes and periods that’d break CSS class names. Works great since it stays in HubL without needing server-side processing, especially handy for dynamic content from HubDB or blog posts.

I encountered a similar challenge when working with HubL templates. The built-in filters such as lower and replace can address basic needs effectively. For instance, using the expression {{ my_text | lower | replace(' ', '-') }} can correctly adjust spaces. However, additional characters like commas and parentheses can complicate the process. To manage these intricacies, I opted to implement custom backend logic utilizing regex. Although it requires a bit more initial effort, this method significantly improves the cleanliness of the final output.