0
0
Ruby on Railsframework~30 mins

Layouts and content_for in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Layouts and content_for in Rails
📖 Scenario: You are building a simple blog page in a Rails app. You want to use a layout to keep the header and footer consistent across pages. You also want to add a custom title and a sidebar only on the blog page using content_for.
🎯 Goal: Create a Rails layout with a header and footer. Use content_for in the blog view to add a page title and a sidebar section. The layout should display these sections if they exist.
📋 What You'll Learn
Create a layout file app/views/layouts/application.html.erb with a header and footer
Use yield to render the main content
Use content_for blocks for :title and :sidebar in the layout
In the blog view app/views/blog/index.html.erb, set content_for :title with the text 'My Blog'
In the blog view, set content_for :sidebar with a list of links
Ensure the layout shows the title in the <title> tag and the sidebar in a <aside> element
💡 Why This Matters
🌍 Real World
Layouts and content_for are used in Rails apps to keep page structure consistent and allow pages to customize parts like titles and sidebars easily.
💼 Career
Understanding layouts and content_for is essential for Rails developers to build maintainable and DRY web applications.
Progress0 / 4 steps
1
Create the layout with header, footer, and yield
Create a file app/views/layouts/application.html.erb with a <header> containing the text 'Welcome to My Site', a <footer> with the text '© 2024 My Site', and a <main> section that uses yield to render page content.
Ruby on Rails
Need a hint?

Use HTML tags <header>, <main>, and <footer>. Inside <main>, add <%= yield %> to show the page content.

2
Add content_for blocks for title and sidebar in layout
In app/views/layouts/application.html.erb, add a <title> tag inside <head> that uses content_for?(:title) ? yield(:title) : 'Default Title'. Below the <main> section, add an <aside> that renders yield(:sidebar) only if content_for?(:sidebar) is true.
Ruby on Rails
Need a hint?

Use content_for?(:title) and yield(:title) inside the <title> tag. Use a conditional if content_for?(:sidebar) to show the <aside> with yield(:sidebar).

3
Set content_for :title in blog index view
In app/views/blog/index.html.erb, add a content_for block for :title that sets the text 'My Blog'.
Ruby on Rails
Need a hint?

Use <% content_for :title do %> and <% end %> to wrap the title text.

4
Set content_for :sidebar with links in blog index view
In app/views/blog/index.html.erb, add a content_for block for :sidebar that contains an unordered list <ul> with three list items <li> containing links: 'Home', 'About', and 'Contact'. Use link_to with '#' as href for each link.
Ruby on Rails
Need a hint?

Wrap the links inside <ul> and <li> tags inside a content_for :sidebar do block.