如何截断html而不破坏标签? [英] How to truncate html without breaking the tags?

查看:215
本文介绍了如何截断html而不破坏标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保所有html标签都已关闭?出现问题是因为我想为每篇文章创建某种摘录.例如,某人写了这样的文章:

How to ensure that all html-tags were closed? The problem arises because I want create some sort of excerpt for every article. For example someone writes an article like this:

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

如果我在标签"之后剪切此消息,则会得到未封闭的标签. 在保存到数据库之前,如何与Django检查所有用户的输入文本?

If I cut this message just after "tags", I get an unclosed tag . How can I check with Django all user's input text before saving it to DB?

推荐答案

在Django 1.7中,有一个名为

In Django 1.7, there is a specific template filter called truncatechars_html:

类似于truncatechars,但它知道HTML标记.任何 在字符串中打开但未在标签之前关闭的标签 截断点在截断后立即关闭.

Similar to truncatechars, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point are closed immediately after the truncation.

另请参见 truncatewords_html .

对于Django <1.7,您可以使用truncatewords_html,也可以基于1.7中实现的过滤器进行自定义过滤( HTML的安全截断.

For Django<1.7, you can either use truncatewords_html, or make a custom filter based on the one implemented in 1.7 (source), or use this snippet (have not tested it). Also see relevant to the snippet blog post: Safe truncation of HTML.

这篇关于如何截断html而不破坏标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆