【问题标题】:django custom filter - replace line break with line spacedjango 自定义过滤器 - 用换行符替换换行符
【发布时间】:2014-12-02 14:58:29
【问题描述】:

如果我的 django 模板中有一个字符串,其格式如下:

Line 1<br />Line 2<br />Line 3<br />Line 4<br />

我想将其格式化为:

Line 1 Line 2 Line 3 Line 4

我想替换换行符()用一个行空间,所以字符串在一行上。

我查看了 django 文档 herehere,但找不到自定义过滤器的可行替换。

有没有人有任何建议或工作示例的链接?

干杯。

编辑 - 更多上下文 - 根据要求

db中存储的字符串是:

Line 1<br />Line 2<br />Line 3<br />Line 4<br />

在django模板中调用的是:

{{ education_detail.education_details_institution_name|truncatechars:20 }}

在浏览器中显示为:

Line 1<br />Line 2<br />Line 3<br />Line 4<br />

【问题讨论】:

  • 请添加更多上下文。包括您的模板和数据。

标签: python django replace newline


【解决方案1】:

这里是用换行符替换换行符的代码。

我遇到的问题是我没有添加 @register.filter(name='replace_linebr')

from django import template

register = template.Library()

@register.filter(name='replace_linebr')
def replace_linebr(value):
    """Replaces all values of line break from the given string with a line space."""
    return value.replace("<br />", ' ')

这是对模板的调用:

{{ education_detail.education_details_institution_name|replace_linebr }}

我希望这对其他人有帮助。

【讨论】:

    【解决方案2】:

    也许应用内置的striptagsremovetags 过滤器? 注意 removetags 在 Django 1.8 中已弃用。

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#removetags (尽管文档似乎都注意到了一些安全警告)

    {% filter removetags:"br" %}
        AA<br/>
        BB<br/>
        CC<br/>
        DD<br/>
    {% endfilter %}
    

    {% filter striptags %}
        AA<br/>
        BB<br/>
        CC<br/>
        DD<br/>
    {% endfilter %}
    

    【讨论】:

    • 谢谢,但是 striptags 和 removetags 会删除标签并将它们替换为空(实际单词之间没有空格),因此这两个标签在这种情况下不可用。字符串的输出将是:Line 1Line 2Line 3Line 4。我想要 Line 1 Line 2 Line 3 Line 4。
    • removetags 在 1.8 中已弃用:“自 1.8 版起已弃用:removetags 无法保证 HTML 安全输出,出于安全考虑已弃用。请考虑改用漂白剂。”
    猜你喜欢
    • 2014-09-10
    • 1970-01-01
    • 2012-05-12
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多