ERB模板中的Chef换行符

时间:2015-08-02 00:50:46

标签: chef newline erb

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

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

我希望它显示为:

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

我打电话的时候:

<%= node['apples'] %>

在我的模板中。换行符\n似乎无法正常工作。这种行为是如何实现的?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

食谱:

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

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

使用rubys 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

答案 1 :(得分:0)

我终于想出了解决这个问题的方法。

问题中描述的场景只是通过附加新的行字符来表示变量中的中断来解决。

因此,变量声明为:

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

将输出到模板:

Cortland,
Red Delicious