【问题标题】:django template string - replace line break with line spacedjango 模板字符串 - 用换行符替换换行符
【发布时间】:2014-09-10 17:58:18
【问题描述】:

我的 django1.4 模板中有一个字符串,我想用空格替换换行符。我只想用模板字符串中的单个空格替换换行符。

到目前为止,我在 django docs、Google 和 SO 上的所有搜索都没有给我答案。

这是我模板中的字符串:

{{ education_detail.education_details_institution_name|safe|truncatechars:20|striptags }}

当我保存了以下字符串时:

University
Bachelor of Something
2008 - 2010

django模板中的字符串渲染为:

UniversityB... 

我想用 yB 之间的空格替换换行符,如下所示:

University B...

我该怎么做?

【问题讨论】:

标签: django string replace django-templates newline


【解决方案1】:

这是我终于可以操作的自定义过滤器代码:

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】:

    您可以依靠内置的truncatechars 过滤器的行为将换行符替换为空格。您只需将字符串的length 作为参数传递,这样您就不会看到您的字符串被缩短了:

    {% with value|length as length %}
        {{ value|truncatechars:length }}
    {% endwith %}
    

    这有点hacky,但只使用内置过滤器。

    如果您需要此类功能可重用,您可以随时写custom filter

    【讨论】:

    • 我正在使用truncatechars_html:40,但仍然有换行符
    猜你喜欢
    • 1970-01-01
    • 2022-11-17
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多