3

Similar to Print in ERB without <%=?

However, the answer there is specific to ruby on rails. Is there a similar capability in vanilla erb?

Here's a use case:

<% [
    'host_perfdata_command',
    'service_perfdata_command',
].each do |var|
    value = instance_variable_get("@#{var}")
    if value
        %><%= "#{var}=#{value}" %><%
    end
end
-%>

While this works, it i%><%=s hard to r%><%ead.

Community
  • 1
  • 1
Phil Frost
  • 3,668
  • 21
  • 29

3 Answers3

1

What is wrong with this:

<% ['host_perfdata_command', 'service_perfdata_command'].each do |var| %>
    <% if (value = instance_variable_get("@#{var}")) %>
        <%= "#{var}=#{value}" %>
    <% end %>
<% end %>
bjhaid
  • 9,592
  • 2
  • 37
  • 47
1

Basically, you need to write directly into the output string. Here's a minimal example:

template = <<EOF
Var one is <% print_into_ERB var1 %>
Var two is <%= var2 %>
EOF

var1 = "The first variable"
var2 = "The second one"
output = nil

define_method(:print_into_ERB) {|str| output << str }

erb = ERB.new(template, nil, nil, 'output')
result = erb.result(binding)

But because I feel obligated to point it out, it is pretty unusual to need this. As the other answers have observed, there are a number of ways to rewrite the template in the question to be readable without directly concating to the output string. But this is how you would do it when it was needed.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • While unfortunately the tool I'm using only allows me to use templates, and I don't want to patch the tool, I can't do this, you have answered the question: it's not possible. It seems I'll have to live with an ugly solution. – Phil Frost Jan 31 '14 at 19:10
  • @PhilFrost: It might yet be possible. If you know the name of the variable ERB is using for output, you can directly concat onto that. I named the variable explicitly for clarity in the example, but if I were in your shoes, I'd try the default of `__erbout`. They probably wouldn't change the name of the variable if they aren't using it like this. So instead of `print_into_ERB str`, just do `__erbout << str`. – Chuck Jan 31 '14 at 20:11
1

Try as follows:

<%= [ 'host_perfdata_command', 'service_perfdata_command' ].map do |var|
    value = instance_variable_get("@#{var}")
    value && "#{var}=#{value}"
end.compact.join( "<br>" ) -%>

Then you can join the array with the string you wish.

NOTE: I strongly recommend you move the code into a helper.

helper:

def commands_hash_inspect
   [ 'host_perfdata_command', 'service_perfdata_command' ].map do |var|
      value = instance_variable_get("@#{var}")
      value && "#{var}=#{value}"
   end.compact.join( "<br>" )
end

view:

<%= commands_hash_inspect -%>
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
  • You're right, this is way too much code to be in ERB. Making a method you can call makes it extremely clear what's going on. – tadman Jan 31 '14 at 19:18