search

Home  >  Q&A  >  body text

Rails: Truncate HTML tag text while preserving link text during database column truncation

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

To shorten large texts and display them completely in a popup window, I used the truncate(comment, length: 50, escape: false) function.

Let us consider two examples:

Example 1: The comment column contains the following plain text with HTML tags. By using escape: false, the 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 the href tag to create the link, but the escape behavior is not working as expected. It doesn't recognize it as an HTML tag, but treats it as plain text:

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

After truncation, the display is as follows:

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

However, the desired result is to truncate only the text within the tag, leaving the link text "ClickToOpenFile" intact.

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

P粉896751037P粉896751037443 days ago540

reply all(1)I'll reply

  • P粉665427988

    P粉6654279882023-09-13 16:54:17

    Use 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>

    reply
    0
  • Cancelreply