Rails:在数据库列中截断带有HTML标记的文本,同时保留链接文本。

huangapple go评论80阅读模式
英文:

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

问题

我有一个名为comment的数据库列,用于存储包含HTML标记的评论。

为了缩短大段文字并在弹出窗口中完整显示它们,我使用了truncate(comment, length: 50, escape: false)函数。

让我们考虑两个示例:

示例1:
comment列包含以下带有HTML标记的纯文本。通过使用escape: false,HTML标记不会被截断,文本会正确显示,包括任何格式,如粗体:

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

示例2:
在这种情况下,我使用了href标记来创建一个链接,但escape的行为不像预期的那样。它不会将其识别为HTML标记,而是将其视为纯文本:

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

截断后,它会显示类似于:

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

然而,期望的结果是仅截断<a>标记内的文本,保持链接文本"ClickToOpenFile"不变。

我尝试过使用rawhtml_safe,但不幸的是,它们没有提供期望的结果。

英文:

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.

答案1

得分: 1

使用 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>'
英文:

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>

huangapple
  • 本文由 发表于 2023年7月3日 14:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定