[英]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.