Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chef newline in ERB templates

I have a variable that I would like to span two lines when output in a Chef ERB template.

So if node['apples'] equals "Cortland, \nRed Delicious, \nGolden Delicious, \nEmpire, \nFuji, \nGala"

I want it to display as:

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

when I call:

<%= node['apples'] %>

in my template. The newline character, \n doesn't seem to work. How is this behavior achieved?

Thanks!

like image 800
James Taylor Avatar asked Nov 10 '22 08:11

James Taylor


1 Answers

You could loop through the a list in the template instead of adding the control characters into the string.

Recipe:

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

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

Template using rubys join to add the characters you need at the end of each element:

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

Result:

$ 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

You can also look at Rubys split to turn the string into an list. http://ruby-doc.org/core-2.2.0/String.html#method-i-split

Edited to add in ,\n as in the original request.

like image 200
erichelgeson Avatar answered Dec 06 '22 11:12

erichelgeson