What is the parsing process for views in rails? I am partially interested in the parsing order with raw html vs ruby code in erb
tags within views.
I would think this is the order that view code is parsed and eventually sent to the requester:
erb
tag during the parsing process: rails resolves it and appends the result to the parsed html (this includes erb
tags referencing helpers)This appears to not be the case. It appears that the view code does a scan for any erb
snippets and parses those first (including references to helpers). After that is taken care of: rails then parses from top to bottom all the view code and sends the result to the requester.
Take this view for example:
# _form.html.erb
<p> Hello World </p>
<p> Foobar </p>
<% if something_is_true %>
<%= some_helper_method_that_returns_html %>
<% end %>
Is this the correct order in how rails figures out views and sends the result to the requester?
erb
snippets
erb
snippets those are resolved/transformed into html and appended to the html viewerb
Follow up Question: Is there an order that erb
tags themselves are resolved? For example: perhaps an erb
tag that references a helper
is resolved first before an erb
tag that iterates through a collection? Or: does Rails always just resolve erb
tags from top to bottom?
You were right to think that the view code would be read from top to bottom and processed in that way. But there is a problem with this approach. ERB is a template engine/library, and for a template engine to be fast it has to work intelligently.
The process of rendering the action goes something like this:
ERB code is processed in an orderly fashion. For ex:
<%= render 'my_header' %>
This is some HTML
<%= render 'my_footer' %>
In this scenario the file _my_header.html.erb
would be processed and injected first and then _my_footer.html.erb
would be processed and injected. ERB tags are resolved from top to bottom.
<%= yield %>
I hope this clears all your questions about the ERB library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With