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.
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.