首页 > 解决方案 > 使用 Yield 和 Ruby 包装 HTML 标签

问题描述

Ruby初学者在这里。

我正在尝试了解产量以及如何在其周围包装 HTML 标记,但我一直遇到此代码的问题。

def tag (tag_name, attributes = nil)
  "<#{tag_name}#{attributes}>#{yield}</#{tag_name}>"
end


style_tag = tag("div", ["class=", "red"]) do
  tag("h1") do
    "Google it"
  end
end

我的输出是:

 "<div[\"class=\", \"red\"]><h1>Google it</h1></div>"

谢谢

标签: arraysrubyyield

解决方案


问题不在于yieldwich 似乎工作正常,而在于 attributes 参数。或者更确切地说,将参数插入到字符串中。

目前你正在做一个隐含的Array.to_s,这是括号的来源。如果您确定属性字符串是正确的,您可以简单...#{attributes.join} ...地将所有元素连接到一个正确的字符串(假设 HTML 语法正确等等)。


推荐阅读