Introduction
Views show data to users in a clear and friendly way. They turn raw information into pages people can read and understand.
Views show data to users in a clear and friendly way. They turn raw information into pages people can read and understand.
<%= @variable %>
<h1>Welcome, <%= @user.name %>!</h1>
<p>Today is <%= Date.today.strftime('%B %d, %Y') %>.</p>
<ul>
<% @items.each do |item| %>
<li><%= item.title %></li>
<% end %>
</ul>This example shows a controller setting a message, and the view displaying it inside a paragraph.
# app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def index @message = "Hello, Rails learner!" end end # app/views/welcome/index.html.erb <h1>Message for you:</h1> <p><%= @message %></p>
Views should only display data, not change it.
Keep logic in controllers or helpers, not in views.
Use partials to reuse view code and keep things tidy.
Views turn data into readable pages for users.
They use special tags to insert Ruby data into HTML.
Controllers prepare data, views present it clearly.
@items = ['apple', 'banana', 'cherry'], what will this view code output?<ul>
<% @items.each do |item| %>
<li><%= item.upcase %></li>
<% end %>
</ul><ul>
<% @products.each do |product| %>
<li><%= product.name %></li>
<% end %>
</ul><ul>
<% @users.each do |user| %>
<li>
<%= user.name %>
<% if user.email.present? %>
(<%= user.email %>)
<% end %>
</li>
<% end %>
</ul>Pass the test and this pattern moves unknown