Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate html without breaking the tags?

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>

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?

like image 958
Sergey Cherepanov Avatar asked Jun 09 '14 02:06

Sergey Cherepanov


People also ask

How do you trim a tag in HTML?

The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.

What is Truncatechars HTML?

In Django 1.7, there is a specific template filter called 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.

What does it mean to strip HTML?

stripHtml( html ) Changes the provided HTML string into a plain text string by converting <br> , <p> , and <div> to line breaks, stripping all other tags, and converting escaped characters into their display values.

How do I strip a string in HTML?

To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.


2 Answers

In Django 1.7, there is a specific template filter called 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.

Also see 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.

like image 183
alecxe Avatar answered Sep 26 '22 15:09

alecxe


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

like image 40
petkostas Avatar answered Sep 26 '22 15:09

petkostas