How to Create and Render Custom Erb Templates
The Embedded Ruby library is very useful for creating reusable template file for rendering data on forms, web pages and more.
You can use ERB for your own custom templates as well.
Usage
Create a template file for use, for example, __template.erb.txt
. You will need to use the ERB syntax to enable the template to render data properly.
# __template.erb.txt
First Name:<%= first_name %>
Last Name:<%= last_name %>
PhoneNumber:<%= phone %>
Next you need to create the class containing the attributes (or methods) specified in the ERB file that will be used as the data source to render. In the above ERB these are first_name
, last_name
and phone
.
class Person
attr_accessor :first_name, :last_name, :phone
TEMPLATE_FILE_PATH = "__template.erb.txt"
def initialize(first_name, last_name, phone)
@first_name = first_name
@last_name = last_name
@phone = phone
end
def render
erb_template_file_path = File.join(TEMPLATE_FILE_PATH)
erb = ERB.new(File.read(erb_template_file_path))
erb.result(get_binding)
end
# disable:rubocop
def get_binding
binding
end
end
ERB reaches into the class’s binding (i.e. get_binding
) and calls the respective methods in order to acquire the values to render.
Example:
ng = Person.new("Nikolai", "Gogol")
File.open("out.txt") { |f| f.puts(ng.render))
This would create a new file out.txt
which writes the resulting render for the ng
object.
// out.txt
Hello Nikolai Gogol