【问题标题】:Is there any way to allow \n in a django template? (bootstrap-popover)有没有办法在 django 模板中允许 \n ? (引导弹出窗口)
【发布时间】:2013-07-26 18:47:09
【问题描述】:

我有这个字符串

{{contact.info}}

值为:

name teste\nteste@teste.com.br\n(11) 11111-1111\n(0) 12312-3123\n(12) 12312-3123\n

在html中我想看:

name teste
teste@teste.com.br<br>
(11) 11111-1111
(10) 12312-3123
(12) 12312-3123

有什么办法吗?

【问题讨论】:

  • 问题不在于模板,而在于 HTML 中的换行符没有任何作用......
  • 有什么办法吗?

标签: python django twitter-bootstrap django-templates popover


【解决方案1】:

使用 autoescape template tag 转义 HTML 换行符 (&lt;br /&gt;)。

此外,由于您没有 html 换行符,您必须按照this answer 中的建议,使用linebreaksbr Django template filter 将文本文件换行符转换为 HTML 换行符。

您的代码应如下所示:

{% autoescape on %}
    {{ contact.info | linebreaksbr }}
{% endautoescape %}

【讨论】:

  • @user2092913 现在应该 ;)
  • 不允许 html 标签,正在打印
  • 哦,当我尝试直接在 html 中打印时它可以工作,但我使用 bootstrap 中的弹出框,占位符可能会做一些事情:data-content="{{contact.info| linebreaksbr}}"
  • 应该可以工作,因为您正在使用 autoesacpe on 转义 html
  • 如果你不渲染它怎么办?我想将\n 字符放在输入字段的value 中。有没有办法用 django 模板语言保留 \n 字符?
【解决方案2】:

您想要linebreaks 过滤器:

{{contact.info | linebreaks}}

话虽如此,如果contact.info 是一个列表会更好 - 然后你可以这样做:

{% for info in contact.info %}
{{ info }}<br />
{% endfor %}

【讨论】:

  • 比你快 4 秒,但你提供了链接,所以有一个 +1。 :)
  • @Wooble - chuckles 你删除了你的帖子,所以我不能 +1 你打我。
  • 不允许 html 标签,正在打印
  • @user2092913 - 您可能需要在 linebreaks 过滤器之后包含一个 | safe(在我看来,这对于您使用的 Django 版本来说是一个错误)。
  • 我在另一个答案中怎么说,我使用 bootstrap 中的弹出框。当它直接在 html 中工作时,但是当我将它放在占位符中时,它不允许 html 标签...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
相关资源
最近更新 更多