Django 模板:智能切片 HTML 内容

Django template: smartly slice the HTML content

我想巧妙地切片HTML内容。

news为例,显示新闻列表的页面如下:

<table>
  <tr><th>Title</th><th>Content</th></tr>
  {% for news in newsList %}
    <tr>
      <td><a href="/news/{{news.id}}/">{{news.title}}</a></td>
      <td>{{news.content | slice:":30" | safe}} ...</td>
    </tr>
  {% endfor %}
</table>

新闻的内容被切分,这样用户将只能看到新闻的一部分。但是如果 slice:":30" 的位置刚好在 HTML 标签中,那就有问题了。

例如news.content的内容如下:

<p>What is Content Marketing?</p>

切片结果为<p>What is Content Marketing?< ...,其中标签<p>未闭合

切片时有什么方法可以保留 HTML 标签吗?

我猜你应该为此使用 truncatechars_html 过滤器 https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatechars-html