Leon's Blogging

Coding blogging for hackers.

Ruby - ERB Template

| Comments

相信學過 rails 一定知道 erb,可以很方便地將 ruby code 寫在 view 中

但不一定是要有 rails 才可以用 erb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#template.rb
require 'erb'

class Template
  def initialize(foo, bar)
    @foo = foo
    @bar = bar
  end

  def open_template
    puts ERB.new(File.read(templates_path), nil).result(binding)
  end

  def templates_path
    File.expand_path("../template.erb", __FILE__)
  end
end

Template.new('hi', 'hello').open_template
1
2
3
#template.erb
1. <%= @foo %>
2. <%= @bar %>
1
2
3
4
#執行
ruby template.rb
#1. hi
#2. hello

也可以利用 erb 來寫設定檔

參考文件:

Comments