django 模板字符串-用行空格替换换行符

标签 django string replace django-templates newline

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

到目前为止,我对 django 文档、Google 和 SO 的所有搜索都没有给我答案。

这是我模板中的字符串:

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

当我保存以下字符串时:

University
Bachelor of Something
2008 - 2010

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

UniversityB... 

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

University B...

我该怎么做?

最佳答案

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

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

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

关于django 模板字符串-用行空格替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844606/

相关文章:

python - 禁止(未设置 CSRF cookie。)Django

javascript - 在javascript中将字符串转换为utf-8

java - 我可以将 Spannable 转换为 Android 中的字符串以加载 ExpandableListView 吗?

regex - 使用sed转换html标签

python - Pipenv安装错误: Command "python setup.py egg_info" failed with error code 1 in

python - 为什么 select_for_update 在并发插入中起作用?

python - 图书的 CSV 解析

c# - 转换为字符串,删除一些部分并转换回 byte[]

python - 更改 .txt 文件中字符串中特定行中的字符

使用 replace_with_na 函数用 NA 替换范围外的值