Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate helper should not escape translations if key end with '.html' or '_html' #244

Open
KaptajnKold opened this issue Nov 20, 2024 · 6 comments

Comments

@KaptajnKold
Copy link

The native Rails translation helpers (#translate and #t) do not escape translations, if the key ends with _html or .html.. Phlex should mirror this behavior.

In my toy project, I have overridden Phlex's translation helper from this:

def translate(key, **)
  key = "#{self.class.translation_path}#{key}" if key.start_with?(".")
  
  helpers.t(key, **)
end

to this:

def translate(key, **)
  key = "#{self.class.translation_path}#{key}" if key.start_with?(".")

  if key.end_with?("_html") || key.end_with?(".html")
    raw(helpers.t(key, **))
  else
    helpers.t(key, **)
  end
end

which seems to do the trick.

@stephannv
Copy link
Contributor

@KaptajnKold which version are you using? This was fixed on main branch.

@KaptajnKold
Copy link
Author

@stephannv I'm using version 2.0.0.beta2

@stephannv
Copy link
Contributor

@stephannv I'm using version 2.0.0.beta2

if you change your gemfile to gem "phlex-rails", github: "phlex-ruby/phlex-rails", branch: "main" you will get the fix.

@KaptajnKold
Copy link
Author

@stephannv I've tried that now, but it doesn't appear to make a difference; the translations still get escaped.

@stephannv
Copy link
Contributor

That's strange, I'm using Phlex Rails from main and I could remove my monkey patch similar to yours.
Now my code is just:

include Phlex::Rails::Helpers::T

def view_template
  span(class: "mb-2 text-sm text-gray-500") { t(".label_html") }
end

This should work because t(.label_html) returns a ActiveSupport::SafeBuffer object, and Phlex::Rails adds Phlex::SGML::SafeObject module to ActiveSupport::SafeBuffer class, so Phlex can understand that SafeBuffer objects should not be escaped.

Related code:
https://github.com/phlex-ruby/phlex-rails/blob/main/lib/phlex/rails.rb#L36
https://github.com/rails/rails/blob/main/activesupport/lib/active_support/html_safe_translation.rb

Can you provide a MRP?

@KaptajnKold
Copy link
Author

Strange indeed. I tried forking plex-rails figuring I could create a test case demonstrating the problem, but I couldn't, because within that project, it works fine just like you said. The project where I'm experiencing this issue is a Rails 7.1.3.3 project that uses Phlex components in plain old ERB layouts. I'll try to find some time to create a MRP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants