Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate HTML files with ERB?

Tags:

html

ruby

erb

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?

like image 929
blackghost Avatar asked Dec 11 '22 04:12

blackghost


1 Answers

#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
like image 78
7stud Avatar answered Dec 29 '22 20:12

7stud