如何将Python列表转为Django模板中的JavaScript Slug数组?
The problem with your existing attempts is that Django’s built-in filters like slugify operate on the entire list (or joined string) instead of processing each element individually. Here’s how to fix this properly:
Correct Template Code
Use a Django template loop to handle each category one by one, slugify it, and build the JavaScript array correctly:
var categories = [ {% for category in categories %} "{{ category|slugify|escapejs }}"{% if not forloop.last %},{% endif %} {% endfor %} ];
Why This Works:
- We loop through every item in the
categorieslist with Django’s{% for %}tag. - For each category,
slugifyconverts spaces to hyphens and cleans up the string to match your desired format. - The
escapejsfilter adds safety by escaping any special characters (like quotes or backslashes) that could break the JavaScript syntax. - We only add commas between elements if it’s not the last item, using
{% if not forloop.last %}to avoid a trailing comma.
Why Your Previous Attempts Failed:
First approach:
["{{ categories|join:'", "'|slugify }}"]
This joins the entire list into a single string first, then appliesslugifyto the whole thing. You end up with one long slug instead of individual slugified items.Second approach:
["{{ categories|slugify|join:'", "' }}"]slugifyis designed for single strings, not lists. Applying it directly to the list does nothing—you just end up joining the original category names without any slugification.
Alternative: Custom Template Filter (For a One-Liner)
If you prefer avoiding a loop, create a custom filter to apply slugify to each element in the list:
- In your Django app, make a
templatetagsdirectory with__init__.pyand a file likecustom_filters.py:
from django import template from django.template.defaultfilters import slugify register = template.Library() @register.filter def slugify_list(lst): return [slugify(item) for item in lst]
- Load the filter in your template:
{% load custom_filters %}
- Use it in your JavaScript:
var categories = ["{{ categories|slugify_list|join:'", "'|escapejs }}"];
This will slugify each element first, then join them into the correct JavaScript array format.
内容的提问来源于stack exchange,提问作者NaturalBornCamper

