将带有 ruby 变量的 html 文本片段链接到 html 文件



我有一段包含一些 ruby 变量的 html 文本,并且依赖于迭代次数未知的循环。我现在拥有的(和工作(:

测试.rb (件(

head = <<-HEAD
  <html>
    <head>
      <title>Title</title>
      <link rel="stylesheet" type="text/css" href="style.css">
      <script src="scripts.js" type="text/javascript"></script>
    </head>
    <body>
  HEAD
body = '<div class="flex-container">'
items.each do |i|
  body << %(
    <div class="container">
      <button id='action#{i.ref}'
        style="background-color: 'inherit';"
        onmouseover="this.id='action'; this.style.background='highlight';"
        onclick="selectItem()"
        onmouseout="this.id='action#{i.ref}'; this.style.background='inherit';"
        value="#{i.root}">
      <img src="#{i.image}" alt="#{i.name}_img">
      <div>#{i.name}</div>
      </button>
    </div>
  )
end
body += '</div></body></html>'
html = head + body

这就是我生成 html 文本的方式。我想有一个单独的 html 文件,并以某种方式将正文中的内容链接到最后一个示例的 ruby 代码,即:

测试.html

<html>
  <head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="scripts.js" type="text/javascript"></script>
  </head>
  <body>
    <div class="flex-container">
       <!-- HERE HAVE SOME LINK TO THE BODY OF test.rb -->
    </div>
  </body>
</html>

有什么提示吗?谢谢。

你的文件测试.html应该有扩展名'html.erb'

test.html.erb

<html>
  <head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="scripts.js" type="text/javascript"></script>
  </head>
  <body>
    <div class="flex-container">
       <%= @body %>
    </div>
  </body>
</html>

test.rb文件中,你应该声明实例变量,方式如下:

@body += '</div></body></html>'

最新更新