You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复博客文本间距异常?Django页面显示问题求助

问题描述

搭建的博客在新建文章页面(new.html)撰写内容时,文本行间距等格式显示正常,但发布后进入详情页面(detail.html)查看时,所有内容无间距堆叠显示,求解决方法。

new.html 代码

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}

<form method="post">
  <style>
    textarea {
  resize: none;
}
  </style>
    {% csrf_token %}

    <div style="margin-top: 15px"></div>
    <fieldset class="form-group">
        <legend class="border-bottom mb-4">Create Post</legend>
          {{ form|crispy }}
        </fieldset>
       
        <div class="form-group">
          <div style="margin-top: 20px"></div>
        <button class="btn btn-outline-info" type="submit">Create</button>
      </div>
</form>
{% endblock %}

detail.html 代码

{% extends "base.html" %}
{% load static %}


{% block content %}

<html>
  <div style="margin-top: 20px"></div>
  <body class="text-center" style="line-height: 2;">
    <article>
      <h1>{{post.title}}</h1>
      <p style="margin-top: 15px;">{{post.body}}</p>
    </article>
  </body>
  <div style="margin-top: 24px"></div>
  <a style="color: darkgray; font-size: 22px;"> <img  src="{% static 'website/icons8-sparkles-25.png'%}"> Written by {{post.author}} <img  src="{% static 'website/icons8-sparkles-25.png'%}"> </a>
</html>

{% endblock %}
解决方法

核心问题是:你在textarea里输入的换行是纯文本格式的\n,但浏览器渲染纯文本时会自动忽略这些换行符,导致内容堆叠。

方案1:用Django过滤器转换换行

修改detail.html中显示文章内容的代码,使用Django内置的过滤器处理换行:

  • 用linebreaks:会把文本分段包裹成<p>标签,自动生成段落间距
    <p style="margin-top: 15px; line-height: 2;">{{ post.body|linebreaks }}</p>
    
  • 用linebreaksbr:仅把换行转换成<br>标签,保留原有段落结构
    <p style="margin-top: 15px; line-height: 2;">{{ post.body|linebreaksbr }}</p>
    

方案2:用CSS样式识别纯文本换行

给显示内容的<p>标签添加white-space: pre-line样式,让浏览器识别纯文本中的换行和段落:

<p style="margin-top: 15px; line-height: 2; white-space: pre-line;">{{ post.body }}</p>

额外优化

detail.html里不要重复写<html>和<body>标签,因为你已经继承了base.html,这些根标签应该在base.html中统一定义,重复嵌套会导致HTML结构混乱,可能影响样式生效。

内容的提问来源于stack exchange,提问作者Rin Hyakuya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:07:45