ERB templates
| Render a string | |
| Render a file | |
| Trim mode | |
| A layout sketch |
Render a string
ERB mixes plain text with Ruby code inside special tags. Tags that start with an equals sign print a value into the output.
Call result with binding so the template sees local variables from the current scope.
require "erb"
name = "Ada"
puts ERB.new("Hello <%= name %>").result(binding)
Render a file
Real templates live in files, not in string literals. Read the file first and pass its content to ERB exactly as before.
Keep one template per file and give it an erb extension so editors highlight the mixed syntax.
require "erb"
name = "Ada"
template = File.read("hello.erb")
puts ERB.new(template).result(binding)
Trim mode
Loops and conditions often leave stray blank lines in the output. Trim mode with a dash removes the newline after a tag.
The dash variant is the default choice for list templates where every extra empty line shows.
require "erb"
items = [1, 2, 3]
template = "<% items.each do |n| %>- <%= n %>\n<% end %>"
puts ERB.new(template, trim_mode: "-").result(binding)
A layout sketch
Pages often share one frame with changing content in the middle. Render the inner part first, then print it inside a layout template.
The content variable carries the inner HTML while the layout adds the shared heading around it.
require "erb"
content = "Hello"
layout = "<h1><%= content %></h1>"
puts ERB.new(layout).result(binding)
Next: WEBrick server
Article author: Arthur Isaev