Search code examples
ruby-on-railscontentplaceholder

Put inline HTML into variable


Is there a way to put an inline HTML in a view into variable? Something like this:

<% t = content_to_var do %>
   <h1>The title</h1>
<% end %>

<% my_var = content_to_var do %>
   <p>Watch this fine results:</p>
   <table>
   <tr><td>Value 1.1</td><td>Value 1.2</td></tr>
   <tr><td>Value 2.1</td><td>Value 2.2</td></tr>
   <tr><td>Value 3.1</td><td>Value 3.2</td></tr>
   </table>
<% end %>

<%= render 'partial', { title: t, contents: my_var }

Please be aware that I know about absence of function named exactly "content_to_var". It is mentioned only for example.

I know about content_for and yield, but want to do the same through locals.

I do not like an idea to do

my_var = '<table><tr><td>Value 1.1</td><td>Value 1.2</td></tr></table>'.html_safe

It looks ugly.


Solution

  • In old versions of Rails you can do

    <% t = capture do %>
      <h1>The title</h1>
    <% end %>
    

    Don't know about newer versions