简体   繁体   中英

Rails - Append content to helper method's block without <%= %>

I'm trying to create a helper method that appends stuff and shows the block inside of it, like this:

def test &block 
   %{<div> 
      <div> Example content </div>
       <p> #{capture(&block)} </div>
     </div>}.html_safe()
end

when I call it like this

<%= test do %>
 **stuff
<% end %>

it works properly, but when I also need to call it from the controller using ERB.new(), and when I do so, I get an error:

the call:

@result = ERB.new(
%{<%= view_context.test do  %>
    <div>content to show inside</div>
  <% end %>}
).result(binding)

the error:

SyntaxError ((erb):2: syntax error, unexpected ')'
ncat(( view_context.test do  ).to_s); _erbout.concat "\n

so I need to call without the " = ", <% test do ... %>, but when I call it like this, the appended content isn't shown

what am I missing?

Maybe using content_tag in your helper would be a better way to do this.

For your error, it may be because you are doing the whole ERB.new(...) in your view, should be in an helper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM