phlex-ruby / phlex-rails

An object-oriented alternative to ActionView for Ruby on Rails.
https://www.phlex.fun
MIT License
229 stars 40 forks source link

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

Open KaptajnKold opened 5 days ago

KaptajnKold commented 5 days ago

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 commented 5 days ago

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

KaptajnKold commented 4 days ago

@stephannv I'm using version 2.0.0.beta2

stephannv commented 4 days ago

@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 commented 4 days ago

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

stephannv commented 4 days ago

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 commented 4 days ago

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.