[英]Replacing a character in Django template
我想改變&
到and
在我的頁面的元描述中。
這是我試過的
{% if '&' in dj.name %}
{{ dj.name.replace('&', 'and') }}
{% else %}
{{ dj.name }}
{% endif %}
這不起作用。 它仍然顯示為&
dj.name.replace('&', 'and')
不能調用帶參數的方法。需要編寫自定義過濾器。
官方指南在這里:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
好的,這是我的示例,比如說,在名為“questions”的應用程序中,我想編寫一個過濾器to_and
,它將字符串中的“&”替換為“and”。
在 /project_name/questions/templatetags 中,創建一個空白的__init__.py
和to_and.py
,如下所示:
from django import template
register = template.Library()
@register.filter
def to_and(value):
return value.replace("&","and")
在模板中,使用:
{% load to_and %}
然后你可以享受:
{{ string|to_and }}
注意,目錄名templatetags
和文件名to_and.py
不能是其他名字。
更有用:
from django import template
register = template.Library()
@register.filter
def replace(value, arg):
"""
Replacing filter
Use `{{ "aaa"|replace:"a|b" }}`
"""
if len(arg.split('|')) != 2:
return value
what, to = arg.split('|')
return value.replace(what, to)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.