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

Strange behaviour when using content_tag in a custom form field. #533

Open
opensourceame opened this issue Dec 21, 2024 · 1 comment
Open

Comments

@opensourceame
Copy link

The form builder for custom tags does not work the way I would expect any kind of Ruby form builder to behave. Consider this code:

content_tag :div do
  content_tag :h1, 'A'  
  content_tag :h2, 'B'
end

From this I expect:

<div><h1>A</h1><h2>B</h2></div>

But I get:

<div><h2>B</h2></div>

The div content tag only returns the output from the last content_tag. This is very strange to me.

Now if I define content tags outside of the div block I get the result I expect:

a = content_tag :h1, 'A' 
b = content_tag :h2, 'B'

content_tag :div do
   a + b
end  

This outputs:

<div><h1>A</h1><h2>B</h2></div>

Is this expected behaviour or a bug? I have used a lot of different form builders in Ruby, and this is the first one that behaves like this, so it seems very counter-intuitive to me.

@spohlenz
Copy link
Member

This is expected behavior, at least for now, though I admit that it can often not be ideal.

Trestle maintains a list of whitelisted helpers --

WHITELISTED_HELPERS = [:row, :col, :render, :tab, :table, :divider, :h1, :h2, :h3, :h4, :h5, :h6, :card, :panel, :well, :turbo_frame_tag]
which when called are automatically appended to the form content.

For other helpers such as content_tag, they'll follow regular ruby logic which is to only use the result of the final line of the block. In order to include both, one option is to call concat to append each line to the output buffer.

content_tag :div do
  concat content_tag(:h1, 'A' )
  concat content_tag(:h2, 'B')
end

This should also work:

content_tag :div do
   content_tag(:h1, 'A') + content_tag(:h2, 'B')
end  

The reason for doing it this way in Trestle is that some helpers (icon is probably the best example) can be passed to form helpers and they shouldn't be appended to the form content just by being called.

I am exploring approaches such as those take in Phlex, though I'm not sure yet if that is the way to go.

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