Search code examples
htmlruby-on-railsrubyruby-on-rails-5truncate

Rails: Truncating HTML-tagged text while preserving link text during truncation in a database column


I have a database column named comment that stores comments containing HTML tags.

To shorten large texts and display them fully in a pop-up, I'm using the truncate(comment, length: 50, escape: false) function.

Let's consider two examples:

Example 1: The comment column contains the following plain text with HTML tags. By using escape: false, HTML tags are not truncated, and the text is displayed correctly, including any formatting such as bold:

<strong>123</strong><br>
\\\<br>
<strong>test</strong>

Example 2: In this case, I'm using an href tag to create a link, but the escape behavior is not functioning as expected. Instead of recognizing it as an HTML tag, it treats it as plain text:

<a href="/uploads/attachments/2211/test.pdf" target="_blank">ClickToOpenFile</a>

After truncation, it displays something like:

<a href="/uploads/attachments/2..

However, the desired outcome is to only truncate the text inside the <a> tag, keeping the link text "ClickToOpenFile" intact.

I have attempted using raw and html_safe, but unfortunately, they did not provide the desired results.


Solution

  • With github.com/hgmnz/truncate_html gem:

    some_html = '<ul><li><a href="http://whatever">This is a link</a></li></ul>'
    truncate_html(some_html, length: 15, omission: '...(continued)')
      => <ul><li><a href="http://whatever">This...(continued)</a></li></ul>