ERB 模板中的 Chef 换行符

Chef newline in ERB templates

我有一个变量,我想在 Chef ERB 模板中输出时跨越两行。

所以如果 node['apples'] 等于 "Cortland, \nRed Delicious, \nGolden Delicious, \nEmpire, \nFuji, \nGala"

我希望它显示为:

Cortland,
Red Delicious,
Golden Delicious,
Empire,
Fuji,
Gala

当我打电话时:

<%= node['apples'] %>

在我的模板中。换行符 \n 似乎不起作用。这种行为是如何实现的?

谢谢!

我终于找到了解决这个问题的方法。

问题中描述的场景只需在变量中附加换行符来表示中断即可解决。

因此,一个变量声明为:

"Cortland, " + 0x0D.chr + 0x0A.chr + "Red Delicious"

将输出到模板为:

Cortland,
Red Delicious

您可以遍历模板中的列表,而不是将控制字符添加到字符串中。

食谱:

$ cat test.rb 
node.set['apples'] = %W(Cortland Red\ Delicious Golden\ Delicious Empire Fuji Gala)

template "test" do
  local true
  source "./test.erb"
end

使用 ruby​​s 的模板 join 在每个元素的末尾添加您需要的字符:

$ cat test.erb 
<%= node['apples'].join(",\n") %>

结果:

$ chef-apply test.rb 
Recipe: (chef-apply cookbook)::(chef-apply recipe)
  * template[test] action create
    - create new file test
    - update content in file test from none to 70d960
    --- test    2015-08-02 12:32:23.000000000 -0500
    +++ /var/folders/r6/9h72_qg11f18brxvpdpn6lbm0000gn/T/chef-rendered-template20150802-76337-130h5sl   2015-08-02 12:32:23.000000000 -0500
    @@ -1 +1,8 @@
        +Cortland,
        +Red,
        +Delicious,
        +Golden Delicious,
        +Empire,
        +Fuji,
        +Gala

您还可以查看 Rubys split 将字符串转换为列表。 http://ruby-doc.org/core-2.2.0/String.html#method-i-split

按照原始请求编辑添加 ,\n