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:
如何确保所有html标签都已关闭?问题出现是因为我想为每篇文章创建一些摘录。例如,有人写了这样的文章:
Hi everyone, I'm just an article and I have few <strong>tags</strong> inside <em>of me</me>
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保存到数据库之前,如何检查所有用户的输入文本?
2 个解决方案
#1
4
In Django 1.7, there is a specific template filter called truncatechars_html
:
在Django 1.7中,有一个名为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.
与truncatechars类似,只是它知道HTML标记。字符串中打开但在截断点之前未关闭的任何标记在截断后立即关闭。
Also see truncatewords_html
.
另请参见truncatewords_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.
对于Django <1.7,您可以使用truncatewords_html,也可以根据1.7(源代码)中实现的自定义过滤器进行自定义过滤,或者使用此代码段(尚未测试)。另请参阅代码段博客文章:安全截断HTML。
#2
1
For Django 1.6 there is truncatewords_html available no need to create a custom filter. https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#truncatewords-html
对于Django 1.6,有truncatewords_html可用,无需创建自定义过滤器。 https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#truncatewords-html
#1
4
In Django 1.7, there is a specific template filter called truncatechars_html
:
在Django 1.7中,有一个名为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.
与truncatechars类似,只是它知道HTML标记。字符串中打开但在截断点之前未关闭的任何标记在截断后立即关闭。
Also see truncatewords_html
.
另请参见truncatewords_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.
对于Django <1.7,您可以使用truncatewords_html,也可以根据1.7(源代码)中实现的自定义过滤器进行自定义过滤,或者使用此代码段(尚未测试)。另请参阅代码段博客文章:安全截断HTML。
#2
1
For Django 1.6 there is truncatewords_html available no need to create a custom filter. https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#truncatewords-html
对于Django 1.6,有truncatewords_html可用,无需创建自定义过滤器。 https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#truncatewords-html