在Rails应用程序中包含动态json-ld标记

时间:2016-08-18 14:11:48

标签: ruby-on-rails ruby

我的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[{},{},{}]

3 个答案:

答案 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+jsonhttp://haml.info/docs/yardoc/file.REFERENCE.html#attribute-methods

:plain过滤器,它不解析过滤的文本。当您不希望以开头的行时,这对于没有HTML标签的大块文本很有用。或-要解析,请参阅文档http://haml.info/docs/yardoc/file.REFERENCE.html#plain-filter