Creating views with embedded Ruby (ERB) templates

One of the primary tasks of a web developer is to create dynamic web pages that can display information from a database or respond to user inputs. In the world of Ruby on Rails, this task is made easy with the help of Embedded Ruby (ERB) templates.

What is an ERB template?

An ERB template is simply an HTML file with Ruby code embedded within it. These templates allow you to mix static HTML with dynamic Ruby code, enabling you to generate dynamic content effortlessly.

The ERB syntax

ERB templates use a specific syntax to identify Ruby code within the HTML markup. To include a Ruby code snippet, you can use the <% %> tags. For example, let's say we want to display the value of a variable name in our view. We can achieve this by writing:

<p>Welcome, <%= name %>!</p>

In the above example, the <%= %> tags are used to output the value of the name variable. Any Ruby code inside these tags will be evaluated and inserted into the final HTML output.

Using loops and conditionals

ERB templates also support Ruby loops and conditionals. For instance, if we have an array of names called users, we can iterate over it and generate a list using the following code:

<ul>
  <% users.each do |user| %>
    <li><%= user %></li>
  <% end %>
</ul>

Similarly, we can use if statements to conditionally display content:

<% if condition %>
  <p>This will be displayed if the condition is true.</p>
<% else %>
  <p>This will be displayed if the condition is false.</p>
<% end %>

By leveraging the power of Ruby, you can create dynamic views that can adapt to various scenarios effortlessly.

Working with partials

In complex projects, views often contain repetitive sections. ERB templates allow you to extract these sections into reusable partials. Partials are small fragments of code that can be included in multiple views.

To include a partial, you can use the <%= render partial: 'name_of_partial' %> syntax. For instance, let's assume we have a partial named _header.html.erb. We can include it in a view by writing:

<%= render partial: 'header' %>

Partial files are typically prefixed with an underscore (_) to signify that they are not standalone views.

Conclusion

Embedded Ruby (ERB) templates are a powerful tool in the Ruby on Rails framework for creating dynamic views. With their ability to mix HTML and Ruby code, they enable developers to effortlessly generate dynamic content, include loops and conditionals, and extract reusable partials. By mastering ERB templates, you can take your web development skills in Ruby on Rails to the next level.

© NoobToMaster - A 10xcoder company