简体   繁体   English

Rails 从 html.erb 模板生成 html 文件

[英]Rails generate html file from html.erb template

I know thas it sounds a little weird.我知道这听起来有点奇怪。 I need to generate an html file based on an html.erb template which has many variables.我需要基于具有许多变量的 html.erb 模板生成 html 文件。 I will give an oversimplified example.我将举一个过于简单的例子。

In my viwes/pages/home.html.erb I have:在我的 viwes/pages/home.html.erb 我有:

<html>
     <h1> <%= @name %> </h1>
</html>

In my pages_controller.rb:在我的 pages_controller.rb 中:

def home
   @name = 'Michaela'
end

When the home funcion is called, it will render the home.html.erb and in the browser, the content will be showed as if it was opnening an.html file that looks like the following:当调用 home 函数时,它会渲染 home.html.erb 并在浏览器中显示内容,就像打开一个 .html 文件一样,如下所示:

<html>
    <h1> Michaela </h1>
</html>

What I need is to generate an plain html file with that content, after @name has been defined, so if instad of being hardcoded, it´s inputted by the user, the.html file defines it´s content accroding to that user input.我需要的是在定义@name之后生成一个带有该内容的普通html文件,所以如果不是硬编码,它是由用户输入的,.html文件根据该用户输入定义它的内容.

As Maxence recommended, I used the render_to_string helper to finally store the generated html into a variable, and manipulate it in that way.正如 Maxence 建议的那样,我使用 render_to_string 帮助器最终将生成的 html 存储到变量中,并以这种方式对其进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM