首页 > 解决方案 > 截断文本而不截断 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>

我尝试了多种方法truncatehtml_safetruncate 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 标签。

标签: ruby-on-rails

解决方案


推荐阅读