简体   繁体   English

在erb中打印时没有'<%=%>'或滑轨上的红宝石

[英]printing in erb without '<%= %>' or ruby on rails

Similar to Print in ERB without <%=? 类似于没有<%=?的ERB中的打印。

However, the answer there is specific to ruby on rails. 但是,答案是特定于铁轨上的红宝石。 Is there a similar capability in vanilla erb? 香草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. 在此有效的同时, it i%><%=s hard to r%><%ead.

What is wrong with this: 这有什么问题:

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

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. 但这是您在需要时执行的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM