在 rails 中循环结构化数据

Loop in structured data in rails

我正在尝试在 rails 中使用结构化数据,但它无法正常工作。下面是我的代码:

<script type="application/ld+json">
<%=
{
  "@context": "http://schema.org",
  "@type": "FAQPage",
  "mainEntity": @faq[:lists].each do |item|
    item[:list].map do |list|
      {
        "@type": "Question",
        "name": list[:heading],
        "acceptedAnswer": {
          "@type": "Answer",
          "text": list[:desc]
        }
      }
    end
  end
}.to_json.html_safe
%>
</script>

我在做什么?

如果你想mainEntity是一个简单的数组(不是数组的数组),你可以试试这个:

<script type="application/ld+json">
<%=
{
  "@context": "http://schema.org",
  "@type": "FAQPage",
  "mainEntity": @faq[:lists].map do |item|
    item[:list].map do |list|
      {
        "@type": "Question",
        "name": list[:heading],
        "acceptedAnswer": {
          "@type": "Answer",
          "text": list[:desc]
        }
      }
    end
  end.flatten # <===== array[array] --> array
}.to_json.html_safe
%>
</script>

参见:https://apidock.com/ruby/Array/flatten