【问题标题】:django two new-line charactersdjango 两个换行符
【发布时间】:2016-07-02 00:33:00
【问题描述】:

我是 django 的新手。我有一个 纯文本,其中包含许多段落,它们是在 django admin 中输入的。 这是痛苦的文字复制自互联网

示例输入

A mysterious landscape phenomenon known as fairy circles has been found in the Australian outback. The fairy circles are characterised by a hexagonal organisation of soil gaps between grass vegetation and seen in the landscape from above.
The beautiful sight cannot be spotted from ground level. Until now, fairy circles have only been documented in the arid landscape of Namibia, Africa.

示例输出:

A mysterious landscape phenomenon known as fairy circles has been found in the Australian outback. The fairy circles are characterised by a hexagonal organisation of soil gaps between grass vegetation and seen in the landscape from above.


The beautiful sight cannot be spotted from ground level. Until now, fairy circles have only been documented in the arid landscape of Namibia, Africa.

当我使用{{ posts.description|linebreaks }}时,它只会给我一个换行符(一个换行符)。在我的 chrome 控制台中,它应该是一个 <br /> 但我想要 2 个换行符

我尝试使用{{ posts.description|linebreaks|linebreaks }},但没有帮助

我应该如何插入 2 个换行符(两个换行符)

任何帮助表示赞赏..在此先感谢

【问题讨论】:

  • 您可以在posts.description中直接保存2个<br />(例如替换\n)并在模板中应用safe过滤器
  • 感谢您的回复..您能否提供一个示例,以便于理解...

标签: python django django-filter


【解决方案1】:

您可以编写自己的自定义标签,类似于换行符(甚至可以复制一些功能)。这很容易但真的不鼓励 - 这就是标准 django 模板过滤器中不存在它的原因。

但除此之外,您甚至可以拆分字符串并根据需要进行渲染:

例如,您可以获得如here 所述的拆分描述。然后渲染描述如下:

{% for line in posts.descirption_as_list %}
{{ line }}<br/><br/>
{% endfor %}

如果你真的想走模板标签过滤器的路线:

@register.filter(name="split_by")
def split_by(value, split_by='\n'):
    return value.split(split_by)

并将其用作

{% for line in posts.descirption|split_by:"\n" %}
{{ line }}<br/><br/>
{% endfor %}

在上面你甚至不需要指定第二个参数(“\n”)。也就是说,您可以按如下方式使用它:

{% for line in posts.descirption|split_by %}
{{ line }}<br/><br/>
{% endfor %}

但是现在这不是很可读,不是吗?明智地选择。

【讨论】:

  • @Coeus 自定义过滤器会有所帮助,但如上所述不是必需的。除非你想做一些真正花哨的过滤器,否则对开发人员来说有点负担过重(我认为)。为什么要对可以由它自己的实例完成的事情使用过滤器标签?一个很好的理由可能是:“我想在其他地方(甚至在任何地方)重用它”。如果是这样的话,那就去吧。
猜你喜欢
  • 2021-02-12
  • 2012-05-12
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多