Generate HTML files with ERB?

If I have a file .html.erb

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 can only get the .html file?

+3


source to share


3 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 can always change the line @name = "John"

to:

print "Enter a name: "
@name = gets.chomp

      

+8


source


The ruby ​​ERB library works with strings, so you will need to read the .erb file in a string, create an ERB object, and then output the result to an html file, passing the current binding to the ERB.result method.

It would look like

my_html_str = ERB.new(@my_erb_string).result(binding)

      



where @my_erb_string

. Then you can write html string to html file.

More details about binding here and about the ERB library here .

0


source


Here's some sample code:

require 'erb'

template = File.read("template.html.erb")

renderer = ERB.new(template)

class Message
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def get_binding
    binding()
  end

end

message = Message.new 'John'

File.open('result.html', 'w') do |f|
  f.write renderer.result message.get_binding
end

      

template.html.erb

is your template file .html.erb and result.html

is the rendered html file.

Some interesting articles you can look at are link1 , link2 .

0


source







All Articles