Rails: Truncate HTML tag text while preserving link text during database column truncation
P粉896751037
P粉896751037 2023-09-12 19:18:11
0
1
453

I have a database column calledcommentthat stores comments containing HTML tags.

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

Let us consider two examples:

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

123
\\
test

Example 2: In this case, I'm using thehreftag to create the link, but theescapebehavior is not working as expected. It doesn't recognize it as an HTML tag, but treats it as plain text:

ClickToOpenFile

After truncation, the display is as follows:

I have tried usingrawandhtml_safe, but unfortunately they do not provide the desired results.

P粉896751037
P粉896751037

reply all (1)
P粉665427988

Use github.com/hgmnz/truncate_html gem:

some_html = '' truncate_html(some_html, length: 15, omission: '...(continued)') => 
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!