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.
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.
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.
<% 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>
<% 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.
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.
Solutions:
erb
<% date = Time.now %>
<p>Today's date is <%= date %>.</p>
```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 %>
```
```erb
<% (1..10).each do |i| %>
<p><%= i %></p>
<% end %>
```
Remember, practice is key to mastering any new concept. Happy coding!