替换 Django 模板中的字符 [英] Replacing a character in Django template

查看:23
本文介绍了替换 Django 模板中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将页面元描述中的 & 更改为 and.

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 %}

这不起作用.它仍然显示为 &

This doesn't work. It still shows as &

推荐答案

dj.name.replace('&', 'and')您不能使用参数调用方法.您需要编写自定义过滤器.

dj.name.replace('&', 'and') You can not invoke method with arguments.You need to write a custom filter.

官方指南在这里:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

好的,这是我的示例,比如说,在名为questions"的应用程序中,我想编写一个过滤器 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__.pyto_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆