Generate HTML files with ERB?

2019-05-11 15:35发布

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?

标签: html ruby erb
3条回答
等我变得足够好
2楼-- · 2019-05-11 15:59

The ruby ERB library operates on strings, so you would have to read the .erb file into a string, create an ERB object, and then output the result into an html file, passing the current binding to the ERB.result method.

It would look something like

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

where @my_erb_string. You could then write the html string into an html file.

You can read more about binding here and about the ERB library here.

查看更多
甜甜的少女心
3楼-- · 2019-05-11 16:05
#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
查看更多
欢心
4楼-- · 2019-05-11 16:07

Here is a 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

The template.html.erb is your .html.erb template file and result.html is the rendered html file.

Some nice articles you can take a look, link1, link2.

查看更多
登录 后发表回答