在Django模板中,可以使用自定義的模板過濾器來實現字符串的拆分。以下是一個簡單的示例,演示如何根據特定的分隔符拆分字符串并在模板中顯示。
首先,在Django應用的templatetags目錄中,創建一個Python模塊,例如extras.py,并定義拆分字符串的模板過濾器:
在你的 Django 應用目錄下創建 templatetags
目錄(和templates同目錄
)和這個文件
example_app/templatetags/extras.py
from django import template
register = template.Library()
@register.filter(name=‘split’)
def split_filter(value, arg):
“”"
Custom template filter to split a string by a delimiter.
:param value: String to split.
:param arg: Delimiter to use.
:return: List of strings.
“”"
return value.split(arg)
然后建一個模塊標記空文件_init_.py
,再在模板中加載這個過濾器并使用它:
{% load extras %}
{% with my_string=“one,two,three” %}
- {% for item in my_string|split:"," %}
- {{ item }}
- {% endfor %}
在這個例子中,my_string
是要拆分的字符串,分隔符是逗號(,
)。split
過濾器按照逗號將字符串拆分,并在for循環中遍歷每個元素,創建一個無序列表。