ERB conditionally includes <% end%> tag
I wonder how to conditionally include the "end" tag
I have many "partial forms" like this
_form_part_x.html.erb (But this is not what I want to do)
<%= form_for(@model) do |f| %> <%= f.some_tag(...) %> <% end %>
In many views, I just need to render one of these guys.
Now the problem is that I want to have another big view for my model, where I am doing all these partial (form_part_1, form_part_2, etc.). In my case, I am using bootstrap tabs and each tab is partial, which in turn will cause multiple partial form_part_x
to create specific fields.
BUT I don't want to have multiple form tags in my HTML, just one big form, so everything is saved at the same time. So before mine, render tabX
I write the code to create the HTML tag and I close it after all the tabs are displayed.
simple_view.html.erb
<%= render 'form_part_x' %>
big_view.html.erb
<%= form_for(something) do |f| %> <%= render 'tab1', f:f %> <%= render 'tab2', f:f %> ... <%= render 'tab5', f:f %> <% end %>
_tab1.html.erb
<%= render 'form_part_10', f:f %> <%= render 'form_part_23', f:f %>
_form_part_x.html.erb (This can be adapted to what I am doing. If I knew how to add <% end%> inside the <% if%> block
So, basically, I thought I could set up my partial elements to conditionally include <%= form_for(@model) do |f| %>
:
<% # These lines help determine whether an HTML `form` tag should be generated or not f ||= false if not f then existing_form = false else existing_form = true %> <% if not existing_form %> # If the partial is called without sending a local f, we want to create the HTML `form` tag <%= form_for(something) do |f| %> <% end %> <%= f.text_field(:some_field) %> <p>Many more stuff</p> <% if not existing_form %> # If the partial is called without sending a local f, we want to CLOSE the newly created HTML `form` tag <!-- I need to add an <% end %> here ! <% end %>
source share
You need to go to the form_special parameters to build the form:
_form_special.html.erb:
<%= form_for(something) do |f| %> <p>Many form-related stuff</p> <%- if case condition depending on the passed arguments as `params` %> <p>If case stuff: for example an additional `render_partial` </p> <%- end %> <% end %>
Another view:
<%= render partial: 'form_special', params: parameters %>
For your specific case, exclude the case to make _form_part_x.html.erb outside of the form, so this would be:
<%= f.text_field(:some_field) %> <p>Many more stuff</p>
And the caller views:
<%= form_for(something) do |f| %> <%= render partial: form_part_x, f:f %> <% end %>
source share