arrays - 使用 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>"
谢谢
解决方案
问题不在于yield
wich 似乎工作正常,而在于 attributes 参数。或者更确切地说,将参数插入到字符串中。
目前你正在做一个隐含的Array.to_s
,这是括号的来源。如果您确定属性字符串是正确的,您可以简单...#{attributes.join} ...
地将所有元素连接到一个正确的字符串(假设 HTML 语法正确等等)。
推荐阅读
- java - 如何在 Spark Java 中创建复杂的 StructType Schema
- python - 我可以过滤 forms.ManyToManyField 中的对象以等于在另一个字段中选择的值吗?
- quarkus - 使用 JPA 存储库时如何解决 javax.enterprise.inject.IllegalProductException
- azure - 通过 SPA 上的 API 调用传递 Azure 令牌 (JWT)
- excel - Excel-VBA 计算字符串中的变量子字符串
- c++ - 在单链表中添加节点(支持前、尾、中添加)
- javascript - 过滤一个对象数组,使没有 2 个对象是相同的
- promise - 使用公理的 try/catch 与 then/catch 之间的区别
- excel - 如何计算具有条件格式字体颜色的单元格
- production-environment - 为什么默认情况下将 `extract_css` 设置为 true 以用于生产?