You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python列表转为Django模板中的JavaScript Slug数组?

Solution: Generate Slugified JavaScript Array from Django List

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 categories list with Django’s {% for %} tag.
  • For each category, slugify converts spaces to hyphens and cleans up the string to match your desired format.
  • The escapejs filter 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:

  1. First approach: ["{{ categories|join:'", "'|slugify }}"]
    This joins the entire list into a single string first, then applies slugify to the whole thing. You end up with one long slug instead of individual slugified items.

  2. Second approach: ["{{ categories|slugify|join:'", "' }}"]
    slugify is 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:

  1. In your Django app, make a templatetags directory with __init__.py and a file like custom_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]
  1. Load the filter in your template:
{% load custom_filters %}
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:57:27