0

我在食谱的节点文件中有一个验证列表

"normal": {
        "Data_list": 'one, two, three, four',
    "tags": [

    ]
}

基于此列表,我想向模板添加值,下面是相同的源代码,但它似乎不是运行 case 和 if 语句,而是将模板中的所有逻辑作为简单文本添加。

<%= [node['data_list']].each do |data|
     case data
     when 'one'
          "this is one and this will be added in template"
     when 'two'
          "this is two and this will be added in template"
     when 'three'
          "this is three and this will be added in template"
     when 'four'
          "this is four and this will be added in template"
     default
          "this is default and this will be added in template"
     end
end %>

任何帮助确定我做错了什么都会很有帮助

4

2 回答 2

0

data_list 的 JSON 数据设置为单个字符串而不是数组。如果我正确理解您的问题,我认为您需要将其用作您的 JSON 数据:

"normal": {
  "data_list": ["one", "two", "three", "four"],
  "tags": []
}
于 2020-07-28T21:55:55.400 回答
0

当我们使用case语句时,我们通常会从其中一个选项中进行选择。通过迭代一个数组,node['data_list']我们将匹配所有或多个条件。

但是,使用 case 语句呈现模板的正确方法是:

<% node['data_list'].each do |data| %>
  <% case data %>
  <% when 'one' %>
    'this is one and this will be added in template'
  <% when 'two' %>
    'this is two and this will be added in template'
  <% when 'three' %>
    'this is three and this will be added in template'
  <% when 'four' %>
    'this is four and this will be added in template'
  <% else %>
    'this is default and this will be added in template'
  <% end %>
<% end %>

注意:由于迭代,任何不匹配的数组项将else多次打印该部分。

当然,要使其正常工作,您必须data_list像 Jeff 建议的那样定义为 Array。

更新

厨师模板中:

  • 裸文本按原样呈现。示例:("this is one.."包括引号)
  • 字符串/变量插值。示例:<%= node['hostname'] %>将呈现主机名
  • 评估 Ruby 代码。示例:<% if true %>评估if语句
于 2020-07-30T13:03:35.957 回答