【问题标题】:How to truncate html without breaking the tags?如何在不破坏标签的情况下截断 html?
【发布时间】:2014-07-29 13:29:15
【问题描述】:

如何确保所有的 html-tags 都被关闭了?出现问题是因为我想为每篇文章创建某种摘录。比如有人写了这样一篇文章:

Hi everyone, I'm just an article and I have few <strong>tags</strong> inside <em>of me</me>

如果我在“标签”之后剪掉这条消息,我会得到一个未闭合的标签。 如何在 Django 中检查所有用户的输入文本,然后再将其保存到 DB?

【问题讨论】:

    标签: python html django django-templates django-template-filters


    【解决方案1】:

    在 Django 1.7 中,有一个名为 truncatechars_html 的特定模板过滤器:

    类似于 truncatechars,除了它知道 HTML 标签。任何 在字符串中打开但在 截断点在截断后立即关闭。

    另见truncatewords_html。

    对于 Djangotruncatewords_html,或基于 1.7 中实现的过滤器(source)制作自定义过滤器,或使用此 snippet(尚未测试)。另请参阅与 sn-p 博客文章相关的内容:Safe truncation of HTML。

    【讨论】:

      【解决方案2】:

      对于 Django 1.6,有 truncatewords_html 可用,无需创建自定义过滤器。 https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#truncatewords-html

      【讨论】:

      • 感谢您的注意,已将其包含在答案中。
      猜你喜欢
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2011-10-05
      • 2015-06-05
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多