slugify Filter

URL

Documentation

Converts a string to a slug, for use in a URL. Specifically, it:

  1. Converts to lowercase ASCII.
  2. Converts spaces to hyphens.
  3. Removes all characters except letters, numbers, underscores, and hyphens.
  4. Strips leading and trailing whitespace.

Variable

blurb_text = 'Aren’t you a smart one?'

Template

{{ blurb_text|slugify }}

Result

arent-you-a-smart-one

Commentary

The slugify filter can be used to coerce an integer in to a string in a template. Consider the following use case:

<select name="order">
  {% for field in order_fields %}
    <option value="{{ forloop.counter0 }}"
      {% if request.GET.order == forloop.counter0|slugify %}selected{% endif %}
    >{{ field }}</option>
  {% endfor %}
</select>

Because order is passed on the querystring, it will be a string, but forloop.counter0 will be an integer, so the two will never be equal. Coercing forloop.counter0 to a string using slugify solves the problem.

An alternative would be to coerce request.GET.order in to an integer using the add filter as shown here.


Did we get something wrong? Is there a use case for the slugify filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:21 p.m. EST