我的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
为[{},{},{}]
答案 0 :(得分:1)
另一种方法是在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>
答案 1 :(得分:0)
使用.map
代替每个,以便它会返回一个数组
并在循环中移动{}
花括号
{
"@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 %>
}
答案 2 :(得分:0)
%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
标签代替了%script
过滤器http://haml.info/docs/yardoc/file.REFERENCE.html#filters,该标签允许我使用定义以下内容的type
来定义其attribute method
类型为application/ld+json
,http://haml.info/docs/yardoc/file.REFERENCE.html#attribute-methods
:plain
过滤器,它不解析过滤的文本。当您不希望以开头的行时,这对于没有HTML标签的大块文本很有用。或-要解析,请参阅文档http://haml.info/docs/yardoc/file.REFERENCE.html#plain-filter