Python 替换 Django 模板中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21483003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing a character in Django template
提问by Unknown Coder
I want to change &to andin the my page's meta description.
我想在我的页面的元描述中更改&为and。
This is what I tried
这是我试过的
{% if '&' in dj.name %}
{{ dj.name.replace('&', 'and') }}
{% else %}
{{ dj.name }}
{% endif %}
This doesn't work. It still shows as &
这不起作用。它仍然显示为&
采纳答案by tcpiper
dj.name.replace('&', 'and')You can not invoke method with arguments.You need to write a custom filter.
dj.name.replace('&', 'and')您不能使用参数调用方法。您需要编写自定义过滤器。
Official guide is here:
官方指南在这里:
https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#registering-custom-filters
https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#registering-custom-filters
Ok, here is my example, say, in an app named 'questions', I want to write a filter to_andwhich replaces '&' to 'and' in a string.
好的,这是我的示例,比如说,在名为“questions”的应用程序中,我想编写一个过滤器to_and,将字符串中的“&”替换为“and”。
In /project_name/questions/templatetags, create a blank __init__.py, and to_and.pywhich goes like:
在 /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")
In template , use:
在模板中,使用:
{% load to_and %}
then you can enjoy:
然后你可以享受:
{{ string|to_and }}
Note, the directory name templatetagsand file name to_and.pycan not be other names.
注意,目录名templatetags和文件名to_and.py不能是其他名称。
回答by 2rs2ts
The documentationsays thus:
该文件如此说:
Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.
因为 Django 有意限制了模板语言中可用的逻辑处理量,所以不可能将参数传递给从模板内访问的方法调用。数据应在视图中计算,然后传递到模板进行显示。
You will have to edit dj.namebeforehand.
您必须dj.name事先进行编辑。
Edit:looks like Pythoner knows a better way: registering a custom filter. Upvote him ;)
编辑:看起来 Pythoner 知道更好的方法:注册自定义过滤器。给他点赞 ;)

