0
0
Ruby on Railsframework~30 mins

Partial templates in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Partial Templates in Rails Views
📖 Scenario: You are building a simple blog application in Rails. You want to display a list of blog posts on the homepage. Each post has a title and a short description. To keep your views clean and reusable, you will use partial templates for each post.
🎯 Goal: Create a Rails view that uses a partial template to render each blog post's title and description. This will help you reuse the post display code easily in other parts of the app.
📋 What You'll Learn
Create a list of posts as an array of hashes in the controller
Create a partial template named _post.html.erb to display a single post's title and description
Render the partial for each post in the main view using render partial: 'post', locals: { post: post }
Pass the correct local variable post to the partial
💡 Why This Matters
🌍 Real World
Partial templates help keep Rails views clean and DRY (Don't Repeat Yourself). They are used in real apps to reuse UI components like posts, comments, or user profiles.
💼 Career
Knowing how to use partials is essential for Rails developers to build maintainable and scalable web applications.
Progress0 / 4 steps
1
Set up the posts data in the controller
In the controller action, create a variable called @posts and assign it an array with these exact hashes: { title: 'First Post', description: 'This is the first blog post.' } and { title: 'Second Post', description: 'This is the second blog post.' }.
Ruby on Rails
Need a hint?

Use an instance variable @posts and assign it an array of hashes with keys :title and :description.

2
Create the partial template _post.html.erb
Create a partial template file named _post.html.erb inside the views folder. Inside it, display the post's title inside an <h2> tag and the description inside a <p> tag. Use the local variable post to access the post data.
Ruby on Rails
Need a hint?

Use ERB tags <%= %> to output post[:title] and post[:description].

3
Render the partial for each post in the main view
In the main view file (e.g., index.html.erb), use a for loop with variable post to iterate over @posts. Inside the loop, render the partial 'post' and pass the current post as a local variable using render partial: 'post', locals: { post: post }.
Ruby on Rails
Need a hint?

Use ERB tags <% %> for the loop and <%= %> to render the partial.

4
Add a container div with aria-label for accessibility
Wrap the posts list in the main view (index.html.erb) inside a <div> with an aria-label attribute set to 'Blog posts list' for accessibility.
Ruby on Rails
Need a hint?

Use a <div> with aria-label="Blog posts list" wrapping the loop.