Template and Layout Files in Ruby on Ruby on Rails
Rails application has concept of the template files which is used to specify footer and header for each other files used in the Rails application. This file is called application.html.erb and it is stored under app/views/layouts/application.html.erb.
You can find the following HTML code inside of it when opening it for the first time after Rails application provisioning.
<html>
<head>
<title>My App</title>
<%=stylesheet_link_tag ‘application’, media: ‘all’, ‘data-turbolinks-track’=>true%>
<%=javascript_include_tag ‘application’, ‘data-turbolinks-track’=>true%>
<%=csrf_meta_tags%>
</head>
<body><%=yield%></body>
</html>
You may probably guess that <%=yield%> tag is designed to every page that uses application.html.erb file to include its content. In addition, you can add your own layouts inside app/views/layouts folder. You can then use this custom layout file by call on it from your custom controller.
class MyOtherController < ActionController:Base
layout ‘custom_layout’
end
Note that application layout is called every time you try to render other views. The reason for this is quite simple and attributed to the fact that each controller is inherited from ApplicationController which in turn relies on application view.
You can also pass different layout to your class action or method by simply calling it via render method
def my_custom_method
@title = “Custom Title”
render layout: ‘my_value_layout’
end
In addition, Rails framework allows Ruby developer to exclude certain actions from calling a specific layout. This is done via except: keyword when used in lieu with layout.
class MyClassController < ActionController:Base
layout ‘my_layout’, except: ‘my_action’
private
def auto_layout
if action_name =~ /my_action_two/
‘other_action_two_layout’
else
‘my_standard_layout’
end
end
You can use action_name as well in order to single out what layout to call upon view rendering.
Finally, Rails framework is versatile enough to give you capability to include footer and header as separate files into your views. It relies on concept of partials to fulfill this task. All partials start with underscore symbol and you can set it as following.
App/views/layouts/_header.html.erb and app/views/layouts/_footer.html.erb
Calling on these two partials is not very difficult and can be accomplished with the following lines of code:
<%= render partial: ‘layouts/header’%> your other content <%= render partial: ‘layouts/footer’%>