【问题标题】:Shortening HTML content python / django缩短 HTML 内容 python / django
【发布时间】:2013-04-06 05:19:44
【问题描述】:

我有一个从数据库中提取 HTML 内容的系统,它看起来像这样:

<p>This is some text</p>
<p>More text</p>
<p>Third Paragraph</p>

在显示它时,它会显示博客文章内容的简短摘要,但现在在显示文本时,我已将字符限制设置为 200 之类的数字,这将导致摘要如下所示:

<p>This is some text</p>
<p>More text</

在任何地方截断内容,可能会破坏网页的其余部分。 python有没有办法关闭所有打开的标签或只获得一定数量的顶级块?例如,2 个块将是前两个 &lt;p&gt;&lt;/p&gt; 标签。我已经看到 word press 在显示文章的简短预览时具有此功能。

【问题讨论】:

    标签: python html django


    【解决方案1】:

    如果您需要在模板中执行此操作,请查看 truncatewords-html:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatewords-html

    或者在其他地方,您可以使用应该适用于大多数用例的底层 django.utils.text.Truncator 类 (https://github.com/django/django/blob/1.7/django/utils/text.py#L65),如果您需要一些自定义行为,请使用该代码作为参考来自己实现它。

    更新

    如果你需要直接使用django.utils.text.Truncator,这就是你实例化和调用words()方法的方式(这正是truncatewords-html过滤器的作用)

    Truncator(value).words(length, html=True, truncate=' ...')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多