用ERB生成HTML文件? [英] Generate HTML files with ERB?
本文介绍了用ERB生成HTML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个如下所示的 .html.erb
文件:
If I have an .html.erb
file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<%= @name %>
</body>
</html>
如何生成一个看起来像这样的HTML文件?
How can I generate an HTML file that looks like this?
<html>
<head>
<title>Test</title>
</head>
<body>
John
</body>
</html>
假如格式是.html.erb,我该如何执行模板(传递name参数)并能够得到一个.html文件?
How can I execute the template (passing the name parameter) given that the format is .html.erb and be able to get just an .html file?
推荐答案
#page.html.erb
<html>
<head>
<title>Test</title>
</head>
<body>
<%= @name %>
</body>
</html>
...
require 'erb'
erb_file = 'page.html.erb'
html_file = File.basename(erb_file, '.erb') #=>"page.html"
erb_str = File.read(erb_file)
@name = "John"
renderer = ERB.new(erb_str)
result = renderer.result()
File.open(html_file, 'w') do |f|
f.write(result)
end
...
$ ruby erb_prog.rb
$ cat page.html
<html>
<head>
<title>Test</title>
</head>
<body>
John
</body>
</html>
当然,为了让事情更有趣,您可以随时更改
Of course, to make things more interesting, you could always change the line @name = "John"
to:
print "Enter a name: "
@name = gets.chomp
这篇关于用ERB生成HTML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文