替换Django模板中的一个字符 [英] Replacing a character in Django template
问题描述
我想在我网页的元描述中将& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp;< / code>更改为
和
。
I want to change &
to and
in the my page's meta description.
这是我尝试的
{% if '&' in dj.name %}
{{ dj.name.replace('&', 'and') }}
{% else %}
{{ dj.name }}
{% endif %}
这不行。仍然显示为& amp; amp;
推荐答案
dj.name.replace('&','和')
您不能使用参数调用方法。您需要编写自定义过滤器。
dj.name.replace('&', 'and')
You can not invoke method with arguments.You need to write a custom filter.
官方指南在这里:
https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#registering-custom-filters
好的,这里是我的例子,在一个名为问题的应用程序中,我想写一个过滤器 to_and
将字符串中的'&'替换为'和'。
Ok, here is my example, say, in an app named 'questions', I want to write a filter to_and
which replaces '&' to 'and' in a string.
在/ project_name / questions / templatetags中,创建一个空白的 __ init__ .py
和 to_and.py
,如下所示:
In /project_name/questions/templatetags, create a blank __init__.py
, and to_and.py
which goes like:
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
不能是其他名称。
Note, the directory name templatetags
and file name to_and.py
can not be other names.
这篇关于替换Django模板中的一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!