ruby-on-rails - 截断文本而不截断 HTML before_save 回调
问题描述
该字符串包含 78 个字符(含 HTML)和 39 个字符(不含 HTML):
<p>I really like the <a href="http://google.com">Google</a> search engine.</p>
我想根据非 HTML 字符数截断这个字符串,例如,如果我想将上面的字符串截断为 24 个字符,输出将是,这个方法将被称为 before_save 回调:
<p>I really like the <a href="http://google.com">Google</a></p>
我尝试了多种方法truncate
,html_safe
但truncate with gsub
每次遇到此错误时都没有成功。
*** NoMethodError Exception: undefined method `truncate' for object
这是我的代码:
class A < ApplicationRecord
before_save :truncate_description
def truncate_description
allowed_characters = self.is_special ? 600 : 400
self.description = self.description.truncate(allowed_characters)
#self.description = raw self.description.truncate(allowed_characters)
#self.description = truncate(self.description, length: allowed_characters, omission: "" , escape: false)
#self.description = truncate(self.description.gsub(/(<[^>]+>)/, ''), allowed_characters)
end
end
我需要具有特定字符限制的 html 字符串,而不会破坏 html,也不要留下打开的 HTML 标签。
解决方案
推荐阅读
- java - 在同一行 JAVA 上获取各种整数输入
- php - Id 没有出现在 ajax 的 url 上
- angular - 从角度材料列表中删除带有标题的项目
- javascript - 如何使用 refresh_token 在 Oauth 2.0 中实现记住我的功能?
- javascript - 如何修复 Discord.JS 中的循环命令
- html - 如何在我的 index.html 中渲染背景图像以使用 Django 使其动态化?
- php - 在laravel中插入多条记录
- pivot - 如何使用数据阶段中的数据透视阶段获取列名和行
- grpc - rpc 错误:代码 = 未知 desc = 永久移动:HTTP 状态代码 301
- reactjs - 无法实现 D3.js 以使用 useRef 进行反应。正确的方法是什么?