If I have an .html.erb
file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<%= @name %>
</body>
</html>
How can I generate an HTML file that looks like this?
<html>
<head>
<title>Test</title>
</head>
<body>
John
</body>
</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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With