user2490003
user2490003

Reputation: 11920

Stripping HTML markup from a translation string

I have some translations that I use in my views. These translations sometimes return very basic HTML markup in them -

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

(Side note: I'm using the fantastic it gem to easily embed markup, and specifically links, in my translations)

What if I wanted to strip the HTML tags in certain cases, like when I'm working with the translation string in my RSpec tests. Is there an HTML strp functionality that will compile and remove that markup?

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

Thanks!

Upvotes: 0

Views: 1156

Answers (2)

aldrien.h
aldrien.h

Reputation: 3635

Depending on where you use it.

strip_tags method not functioning in controllers, models, or libs

It comes up with an error about white_list_sanitizer undefined in the class you’re using it in.

To get around this, use:

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

To shorten this, add something like this in an initializer:

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

Then call it with:

'string'.strip_tags

But if you only need to use it in VIEW, simply:

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

Upvotes: 1

bosskovic
bosskovic

Reputation: 2054

You may want to try strip_tags from ActionView::Helpers::SanitizeHelper

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!

Upvotes: 4

Related Questions