【问题标题】:How to print line breaks in Python Django template如何在 Python Django 模板中打印换行符
【发布时间】:2011-01-19 22:29:11
【问题描述】:
{'quotes': u'Live before you die.\n\n"Dream as if you\'ll live forever, live as if you\'ll die today"\n\n"Love one person, take care of them until you die. You know, raise kids. Have a good life. Be a good friend. Try to be completely who you are, figure out what you personally love and go after it with everything you\'ve got no matter how much it takes." -Angelina Jolie.'}

请注意我的字典中有换行符:\n

如何使用这些换行符显示我的模板?

{{quotes|withlinebreaks\n}}

【问题讨论】:

    标签: python html django templates


    【解决方案1】:

    所有这些答案都没有明确提到应该在显示模板中使用{{ value|linebreaksbr }},即获取请求而不是发布请求。

    所以如果你有一个模板来显示 post.details,那就是

    <h4>Below are the post details</h4>
    
    {{ post.details|linebreaksbr }}
    

    而不是在帖子表单中

    <form method="post">
        {% csrf_token %}
        {{ form|linebreaksbr }}
        <button>Save post</button>
    </form>
    

    遇到同样的问题,在解决后我们决定外面的人可能会觉得它很方便。 编码愉快!

    【讨论】:

      【解决方案2】:

      使用'&lt;br&gt;' 代替/n

      如有需要,您可以发送.replace('/n', '&lt;br&gt;')

      【讨论】:

        【解决方案3】:

        您还可以使用linebreaksbr 过滤器将所有换行符简单地转换为&lt;br&gt; 无需额外的&lt;p&gt;

        例子:

        {{ value|linebreaksbr }}
        

        如果valueJoel\nis a slug,则输出将为Joel&lt;br&gt;is a slug

        Ignacio's answerlinebreaks 过滤器)的区别在于linebreaks 尝试猜测文本中的段落并将每个段落包装在&lt;p&gt; 中,其中linebreaksbr 只是substitutes newlines with &lt;br&gt;

        这是一个演示:

        >>> from django.template.defaultfilters import linebreaks
        >>> from django.template.defaultfilters import linebreaksbr
        >>> text = 'One\nbreak\n\nTwo breaks\n\n\nThree breaks'
        >>> linebreaks(text)
        '<p>One<br />break</p>\n\n<p>Two breaks</p>\n\n<p>Three breaks</p>'
        >>> linebreaksbr(text)
        'One<br />break<br /><br />Two breaks<br /><br /><br />Three breaks'
        

        【讨论】:

        • 这样更好我不知道为什么人们投票给错误的答案。
        【解决方案4】:

        使用linebreaks 过滤器。

        例如:

        {{ value|linebreaks }}
        

        如果值为Joel\nis a slug,则输出将为&lt;p&gt;Joel&lt;br /&gt;is a slug&lt;/p&gt;

        【讨论】:

          猜你喜欢
          • 2022-01-13
          • 1970-01-01
          • 2011-02-06
          • 2018-09-02
          • 2017-08-19
          • 2018-09-04
          • 2021-02-23
          • 2020-12-22
          • 1970-01-01
          相关资源
          最近更新 更多