【问题标题】:Stripping HTML markup from a translation string从翻译字符串中剥离 HTML 标记
【发布时间】:2025-12-04 16:25:01
【问题描述】:

我在我的观点中使用了一些翻译。这些翻译有时会在其中返回非常基本的 HTML 标记 -

t("some.translation")
#=> "This is a translation <a href="/users">with some</a> markup<br />"

(旁注:我正在使用出色的 it gem 在我的翻译中轻松嵌入标记,特别是链接)

如果我想在某些情况下去掉 HTML 标记怎么办,比如在我的 RSpec 测试中使用翻译字符串时。是否有可以编译和删除该标记的 HTML strp 功能?

t("some.translation").some_html_strip_method
#=> "This is a translation with some markup"

谢谢!

【问题讨论】:

    标签: ruby-on-rails internationalization rails-i18n


    【解决方案1】:

    您可能想从 ActionView::Helpers::SanitizeHelper 尝试strip_tags

    strip_tags("Strip <i>these</i> tags!")
    # => Strip these tags!
    
    strip_tags("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
    # => Bold no more!  See more here...
    
    strip_tags("<div id='top-bar'>Welcome to my website!</div>")
    # => Welcome to my website!
    

    【讨论】:

      【解决方案2】:

      取决于你在哪里使用它。

      strip_tags 方法在 controllersmodelslibs

      中不起作用

      它在您使用它的类中出现关于 white_list_sanitizer 未定义的错误。

      要解决这个问题,使用

      ActionController::Base.helpers.strip_tags('string')
      

      要缩短它,请在初始化程序中添加类似这样的内容:

      class String
        def strip_tags
          ActionController::Base.helpers.strip_tags(self)
        end
      end
      

      然后用调用它:

      'string'.strip_tags
      

      但如果你只需要在VIEW中使用它,只需:

      <%= strip_tags(t("some.translation"))  %>
      

      【讨论】: