堆栈溢出
我正在尝试找出如何以“结构化随机顺序”打印一些YML数据的noob问题。我的意思是我使用Contenful CMS在lookbook中订购内容(https://www.contentful.com/blog/2015/09/10/creating-a-digital-lookbook/) 时尚。
内容编辑者可以选择拖放模块的显示顺序。因此,YML数据的顺序将始终不同。
快速模拟我想要实现的目标:
目前这是数据的外观
:caseModules:
- :id: 2sY3tXCqSIcIM2IUgqCCgG
:quoteBody: Either you run the day or you day runs you
:quoteOriginName: Ghandi
:quoteDate: !ruby/object:DateTime 2017-03-23 00:00:00.000000000 Z
- :id: 2qpSXdyiqg8iQucGoQweio
:caseImage:
:title: Test image title
:description: Test image description
:url: "//images.contentful.com/d65nu5c5ibm8/3l2tizTPRSACEIUK0OugUi/65a718dfa621cb6d1d384251ef83a787/account.png"
:caseImageName: Test image title
:caseImageCaption: This test image is a nice example of how we want to showcase
images on the page
- :id: 3HaLvYSEs86ACoqMYE0QSk
:header: Header
:body: "There are previous versions because you haven't made changes to this entry
yet. As soon as you publish changes, you'll be able to compare different versions.\n\n"
- :id: 6HASpa0o3SkyMK4gYgIq8W
:quoteBody: This is another quote
:quoteOriginName: Sebastian Graz
:quoteDate: !ruby/object:DateTime 2019-01-19 00:00:00.000000000 Z
- :id: 3D6Gx2qphK6qAI2qyYGcwK
:caseImage:
:title: king-fisher
:description: With King Fisher we managed to create an unique experience using
Spindrift Site Builder
:url: "//images.contentful.com/d65nu5c5ibm8/5kCjQiyCv6m00m0m46UWi4/ce4ab4cdc8ade1fd63f3e564def42e45/king-fisher.png"
:caseImageName: King Fisher case image name
:caseImageCaption: King fisher image caption
我使用.erb来打印数据,如下所示:
<% data.site.container.each do | _, project| %>
<%= project['caseModules']%>
<% end %>
这在前端给了我这个。
[# quoteOriginName="Ghandi">, # caseImageCaption="This test image is a nice example of how we want to showcase images on the page" caseImageName="Test image title" id="2qpSXdyiqg8iQucGoQweio">, #, # quoteOriginName="Sebastian Graz">, # caseImageCaption="King fisher image caption" caseImageName="King Fisher case image name" id="3D6Gx2qphK6qAI2qyYGcwK">]
我希望我可以做类似的事情:
<% data.site.container.each do | _, project| %>
<% project['caseModules'].each do | image | %>
<%= image['caseImage']['url']%>
<% end %>
<% end %>
但我收到错误:undefined method `[]' for nil:NilClass
所以我想知道是否有人可以给我一些关于我做错的指针。我应该使用开关盒来渲染不同的块吗?我在<%= image['caseImage']['url']%>
语法中做错了它不起作用吗?
感谢任何帮助
编辑:
我最终使用has_key?
并且它有效。
<% data.site.container.each do | id, container| %>
<% container.caseModules.each do | caseModules | %>
<% if caseModules.has_key?("caseImage") && caseModules["caseImage"]%>
<img src="<%= caseModules.caseImage['url'] %>" alt="" />
<% end %>
<% if caseModules.has_key?("quoteBody") && caseModules["quoteBody"]%>
<%= caseModules.quoteBody %>
<% end %>
<% if caseModules.has_key?("body") && caseModules["body"]%>
<%= caseModules.body %>
<% end %>
<% end %>
<% end %>
答案 0 :(得分:1)
问题是YAML文件中的键是符号而不是字符串,将其替换为project[:caseModules]
或project.caseModules
,其中任何一个都可以正常工作。