替换Django模板中的字符

Unk*_*der 6 python django django-templates

我想改变&and在我的网页的meta描述.

这是我试过的

{% if '&' in dj.name %}
    {{ dj.name.replace('&', 'and') }}
{% else %}
    {{ dj.name }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

tcp*_*per 23

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

官方指南在这里:

https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#registering-custom-filters

好的,这是我的例子,比如说,在一个名为'questions'的应用程序中,我想编写一个过滤器to_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")
Run Code Online (Sandbox Code Playgroud)

在模板中,使用:

{% load to_and %}
Run Code Online (Sandbox Code Playgroud)

然后你可以享受:

{{ string|to_and }}
Run Code Online (Sandbox Code Playgroud)

注意,目录名templatetags和文件名to_and.py不能是其他名称.

  • 我想如果你写一个示例过滤器会更好。 (2认同)

mrv*_*vol 18

更有用:

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)


Run Code Online (Sandbox Code Playgroud)


2rs*_*2ts 5

文档这样说的:

由于 Django 有意限制模板语言中可用的逻辑处理量,因此无法将参数传递给从模板内访问的方法调用。数据应在视图中计算,然后传递到模板进行显示。

您必须dj.name事先进行编辑。

编辑:看起来Pythoner知道一个更好的方法:注册一个自定义过滤器。给他点赞;)