require "erb"
# build data class
class Listings
PRODUCT = { :name => "Chicken Fried Steak",
:desc => "A well messages pattie, breaded and fried.",
:cost => 9.95 }
attr_reader :product, :price
def initialize(product = "", price = "")
@product = product
@price = price
end
def build
b = binding
# create and run templates, filling member data variables
ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
<%= PRODUCT[:name] %>
<%= PRODUCT[:desc] %>
END_PRODUCT
ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
<%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
<%= PRODUCT[:desc] %>
END_PRICE
end
end
# setup template data
listings = Listings.new
listings.build
puts listings.product + "\n" + listings.price
Chicken Fried Steak
A well messages pattie, breaded and fried.
Chicken Fried Steak -- 9.95
A well messages pattie, breaded and fried.
require 'erb'
# 准备条件
class User
attr_accessor :name
def initialize(name)
@name = name
end
end
# 设置实例变量
@user = User.new("Kelby")
# 打包环境
binder = self.send(:binding) # 调用 :binding 私有方法
# 模板
template = "Hello, <%= @user.name %>"
# 渲染器(名词)
render = ERB.new(template)
# 渲染(动词)
render.result(binder)
# 输出结果
=> "Helo, Kelby"