Home>

Can you do things like defining simple methods in Rails view?

<div>
<% = render 'item1'>
</div
<div>
<% = render 'item2'>
</div
<div>
<% = render 'item3'>
</div>



Make it a method

<% = fg item1%>
<% = fg item2%>
<% = fg item3%>


Can't you put it like?

<% def fg do | item |%>
<div><% = render item%></div>
<% end%>


It does n’t seem to be ...

If i use bootstrap, even if I want to change the layout a little
Since it is necessary to rewrite the classes of all parts scattered around the view
Is there a good management method?

Addition:

Partial was used only as a sample
What we want to share is class ="form-group col-auto col-sm-2 col-lg-1 ..."

For example

<ul>
<li>
...
</li>
<li>
...
</li
<li>
...
</li>


It's okay, but if you use bootstrap you have to specify the same class many times
As soon as I thought it would be nice to use the features on the Rails side

Furthermore, if this li is made into individual parts and scattered in the partial view,
You have to change 3 files each time you change the layout (p-1) ...

Before using bootstrap for the first time so far
ul.myclass>li {...} and CSS were just enough to separate the HTML and adjust the layout ...

  • Answer # 1

    How about using a helper that receives a block?

    def fg (&block)
      content_tag (
        : div,
        capture (&block),
        class: ["form-group" "form-control-sm" "col-sm-2" "col-md-2" "col-lg-1"]
      )
    end
    <% fg do%>
      <% = render 'item1'>
    <% end%>

  • Answer # 2

    Investigate partials.

    Learn how to make and learn Ruby on Rails Vol.19 partials!

      

    ...
      By using partials, you can combine similar code in View into one.
      ...