通过一个简单的示例演示如何通过erb.html或者html.erb模板文件,通过ruby erb模块的动态绑定生成html文件。
HelloJohn.erb.html即模板文件,name.rb文件为模板文件中的变量,test.rb将变量和模板文件进行动态绑定,输出html文件,结果如下图。
#HelloJohn.erb.html文件
<html>
<head>
<title>Test</title>
</head>
<body>
<%= @name%>
</body>
</html>
#name.rb文件
@name = "Hello,John!"
#test.rb
require 'erb'
require './name'
# read in template
html_in_path = "./john.html.erb"
html_in = ""
File.open(html_in_path, 'r') do |file|
html_in = file.read
end
# configure template with variable values
renderer = ERB.new(html_in)
html_out = renderer.result(binding) #动态绑定
# write html file
html_out_path = "./HelloJohn.html"
File.open(html_out_path, 'w') do |file|
file << html_out
# make sure data is written to the disk one way or the other
begin
file.fsync
rescue
file.flush
end
end
#生成html执行下面代码
ruby test.rb
更多推荐
Ruby erb模板文件生成html网页的示例
发布评论