Text Templates in Ruby

Ruby offers built-in support for creating dynamic content or showing customized output to the user with the ERB (Embedded Ruby) library. ERB is commonly used for generating HTML, but it can be used for any text generation purpose.

require 'erb'

# We can create a new ERB template and parse its body from a string.
# Templates are a mix of static text and Ruby code enclosed in <%= ... %>
# that are used to dynamically insert content.
t1 = ERB.new("Value is <%= @value %>\n")

# We can use the result method to generate the text with specific values.
@value = "some text"
puts t1.result(binding)

@value = 5
puts t1.result(binding)

@value = ["Ruby", "Python", "JavaScript", "C#"]
puts t1.result(binding)

# If the data is a hash we can use the <%= @hash[:key] %> syntax to access
# its values.
t2 = ERB.new("Name: <%= @person[:name] %>\n")

@person = { name: "Jane Doe" }
puts t2.result(binding)

@person = { name: "Mickey Mouse" }
puts t2.result(binding)

# Ruby's if/else can be used for conditional execution in templates.
t3 = ERB.new("<% if @value %>yes<% else %>no<% end %>\n")

@value = "not empty"
puts t3.result(binding)

@value = ""
puts t3.result(binding)

# We can use Ruby's each method to loop through arrays or hashes.
t4 = ERB.new("Range: <% @array.each do |item| %><%= item %> <% end %>\n")

@array = ["Ruby", "Python", "JavaScript", "C#"]
puts t4.result(binding)

When you run this script, you’ll see the following output:

Value is some text
Value is 5
Value is ["Ruby", "Python", "JavaScript", "C#"]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Ruby Python JavaScript C# 

In this Ruby example, we’ve used ERB (Embedded Ruby) to create templates, which is analogous to the text/template package in the original example. ERB allows us to embed Ruby code within strings, which is then evaluated when the template is rendered.

We’ve maintained the structure of the original example, demonstrating how to create templates, use variables, work with conditionals, and iterate over collections. The syntax is different, but the concepts are similar:

  • Instead of {{.}}, we use <%= @variable %> to insert values.
  • Conditional statements use <% if condition %>...<%else%>...<%end%>.
  • Loops use <% @array.each do |item| %>...<%end%>.

Ruby’s ERB is more flexible in some ways, as it allows any Ruby code to be embedded and executed within the template. However, this also means that care must be taken to ensure that templates don’t execute unsafe code, especially when working with user input.