Generate HTML files with ERB?

。_饼干妹妹 提交于 2019-12-10 10:11:58

问题


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?


回答1:


#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



回答2:


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:


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.



来源:https://stackoverflow.com/questions/25274612/generate-html-files-with-erb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!