ruby-on-rails – Rails i18n项目列表和循环视图
发布时间:2020-12-16 23:29:21 所属栏目:百科 来源:网络整理
导读:如何在yml中列出元素并在视图中循环它们并访问它们的属性?我当前的代码只获取列表中的最后一项.我想在视图中循环遍历项目列表并显示其标题和描述元素. 例如 阳明: en: hello: "Hello world" front_page: index: description_section: title: "MyTitle" ite
如何在yml中列出元素并在视图中循环它们并访问它们的属性?我当前的代码只获取列表中的最后一项.我想在视图中循环遍历项目列表并显示其标题和描述元素.
例如 阳明: en: hello: "Hello world" front_page: index: description_section: title: "MyTitle" items: item: title: "first item" description: "a random description" item: title: "second item" description: "another item description" 视图: <%= t('front_page.index.description_section.items')do |item| %> <%= item.title %> <%= item.description %> <%end %> 结果: {:item=>{:title=>"second item",:description=>"another item description"}} 期望的结果: first item a random description second item another item description 解决方法
请改用:
<% t('front_page.index.description_section.items').each do |item| %> # ^ no equal sign here <%= item[:title] %> #^^^^ this is a hash <%= item[:description] %> <% end %> 此外,您的商品列表未正确定义: t('front_page.index.description_section.items.item.title') # => returns "second item" because the key `item` has been overwritten 使用以下语法在YAML中定义数组: items: - title: "first item" description: "a random description" - title: "second item" description: "another item description" 要检查这一点,您可以在IRB控制台中执行此操作: h = {:items=>[{:title=>"first item",:description=>"desc1"},{:title=>"second item",:description=>"desc2"}]} puts h.to_yaml # => returns --- :items: - :title: first item :description: desc1 - :title: second item :description: desc2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |