我的show.html.erb中有以下代码片段
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Person",
"name": "<%= @person_name %>",
"logo": "<%= @person_img_url %>",
"membersOf":[
{
<%= @person_orgs.each do |group| %>
"@context": "http://schema.org",
"@type": "Organization",
"name": "<%= group[:name] %>"
"logo": "<%= group[:img_url] %>",
"url": "https://siftery.com/groups/<%= group[:handle] %>"
<% end %>
}
]
}
我得到的membersOf输出是[{}{}{}],它不是一个数组,而是一个缺少逗号的字符串。我应该如何更正才能使membersOf成为[{},{},{}]
发布于 2020-03-15 18:11:03
另一种方法是在Ruby中构建对象并将其转换为JSON。这样做的好处是可以安全地避开所有参数,而且看起来更整洁。
<script type="application/ld+json">
<%=
{
:@context => "https://schema.org",
:@type => "Person",
:name => @person_name,
:logo => @person_img_url,
:membersOf => @person_orgs.map do |group|
{
:@type => "Organization",
:name => group[:name],
:logo => group[:img_url],
:url => "https://siftery.com/groups/#{group[:handle]}"
}
end
}.to_json.html_safe
%>
</script>发布于 2016-08-18 22:55:00
使用.map而不是each,这样它将返回一个数组
并在循环内移动{}大括号
{
"@context": "http://schema.org",
"@type": "Person",
"name": "<%= @person_name %>",
"logo": "<%= @person_img_url %>",
"membersOf": <%= @person_orgs.map do |group| %>
{
"@context": "http://schema.org",
"@type": "Organization",
"name": "<%= group[:name] %>"
"logo": "<%= group[:img_url] %>",
"url": "https://siftery.com/groups/<%= group[:handle] %>"
}
<% end %>
}发布于 2019-06-23 00:36:15
%script{type: "application/ld+json"}
:plain
{
"@context": "http://schema.org",
"@type": "Person",
"name": "<%= @person_name %>",
"logo": "<%= @person_img_url %>",
"membersOf":[
{
<%= @person_orgs.each do |group| %>
"@context": "http://schema.org",
"@type": "Organization",
"name": "<%= group[:name] %>"
"logo": "<%= group[:img_url] %>",
"url": "https://siftery.com/groups/<%= group[:handle] %>"
<% end %>
}
]
}我没有使用:javascript过滤器http://haml.info/docs/yardoc/file.REFERENCE.html#filters,而是使用了%script标记,它允许我通过使用将类型定义为application/ld+json,http://haml.info/docs/yardoc/file.REFERENCE.html#attribute-methods的attribute method来定义它的type
:plain筛选器,它不会解析过滤后的文本。这对于没有HTML标签的大文本块非常有用,因为您不希望行以开头。或者-要进行解析,请参阅文档http://haml.info/docs/yardoc/file.REFERENCE.html#plain-filter
https://stackoverflow.com/questions/39020469
复制相似问题