Creating Views with ERB Templates

Tutorial 1 of 5

1. Introduction

In this tutorial, we will focus on creating dynamic views using Embedded Ruby (ERB) templates in a Rails application. ERB is a templating system that allows you to write Ruby code within your HTML files. This makes your views dynamic, meaning they can change based on the data passed into them.

By the end of the tutorial, you will understand how to:
- Create and use ERB templates
- Embed Ruby code within HTML
- Generate dynamic HTML content

Prerequisites: You should have Ruby, Rails, and a basic understanding of HTML.

2. Step-by-Step Guide

2.1 ERB Syntax

ERB has two tags:
- <% %>: Executes the Ruby code inside it but does not output anything to the template.
- <%= %>: Executes the Ruby code and also outputs the result to the template.

2.2 Creating a New ERB File

ERB files are typically placed in the app/views directory. They should have the extension .html.erb, indicating they are HTML files with embedded Ruby.

3. Code Examples

3.1 Basic ERB Syntax

<% title = "Hello, Rails!" %>
<h1><%= title %></h1>

In the above code:
- The first line sets a variable title with the value "Hello, Rails!".
- The second line outputs the value of title within an <h1> tag.
- The result will be: <h1>Hello, Rails!</h1>

3.2 Using Ruby Logic in ERB

<% if true %>
  <p>This will always be displayed.</p>
<% else %>
  <p>This will never be displayed.</p>
<% end %>

In this example:
- We use an if statement to conditionally display HTML.
- The true condition always evaluates to true, so the first paragraph is displayed.
- The second paragraph, within the else clause, is not displayed.

4. Summary

We've covered the basics of using ERB in Rails, including its syntax, creating ERB files, and embedding Ruby code within HTML. Your next steps could include learning more about Rails, such as how to use models and controllers, or further exploring ERB's capabilities.

5. Practice Exercises

  1. Create an ERB file that calculates and displays today's date.
  2. Create an ERB file with a form that asks for the user's name and displays a personalized greeting.
  3. Create an ERB file that uses a loop to display a list of numbers from 1 to 10.

Solutions:

  1. erb <% date = Time.now %> <p>Today's date is <%= date %>.</p>

  2. ```erb
    <form>
      <label for="name">What's your name?</label>
      <input id="name" name="name" type="text">
      <input type="submit" value="Submit">
    </form>
    <% if params[:name] %>
      <h1>Hello, <%= params[:name] %>!</h1>
    <% end %>
    ```
    
  3. ```erb
    <% (1..10).each do |i| %>
      <p><%= i %></p>
    <% end %>
    ```
    

Remember, practice is key to mastering any new concept. Happy coding!