HTML truncation with fluid

I am using the Liquid templating engine to display a summary series of messages - at the moment I have something like that:

{% for page in site.posts %} {{page.content | truncatewords: 100}} {% endfor %} 

The content of the page contains HTML, and using truncatewords can cause HTML to be inserted into the output file. I don’t want to remove all the HTML from the content (embedded videos and images should be visible), and ideally all I want is to add closing tags.

I see that simply truncating will not achieve the expected result, so my question is: how can I crop my HTML to display valid markup using Liquid?

Update

A very specific problem is that I have sample code that is marked with pigments. Now, if truncation occurs in the middle of the code sample, it leaves several tags open, messing up the rest of the page. I'm looking for a way to truncate these messages without deleting the entire sample code - just to truncate and close all open tags in the body of the content.

+4
source share
1 answer

OK, therefore, not being able to find a way to do this on the Internet, I prepared my own solution using Nokogiri, and the first step is to cross the HTML node syntax tree.

TruncateHTML is a simple script that allows you to crop a piece of HTML while maintaining a valid structure.

+6
source

Source: https://habr.com/ru/post/1345724/


All Articles