erb模板在代码评估中打印换行符

时间:2019-02-01 11:02:08

标签: ruby erb

生成动态内容文件的木偶erb模板:

<%
if @interfaces.count(',') > 0 then
  counter = 0
  @interfaces.split(',').each do |int|
  next if int == "lo"
  if has_variable?("ipaddress_#{int}")
    ip   = scope.lookupvar("ipaddress_#{int}")
    mask = scope.lookupvar("netmask_#{int}")
    cidr = scope.call_function('netmask_to_masklen',["#{mask}"])
    cidr_to_n = scope.call_function('cidr_to_network',["#{ip}/#{cidr}"])
    if ip =~ /192.168.0/
       x = ip
       $i1 = int
       $c_to_n1 = cidr_to_n
    else
       $y = ip
       $i2 = int
       $c_to_n2 = cidr_to_n
    end
  end
  end
end -%>
ip route add <%= $c_to_n1 %>/<%= $cidr %> dev <%=$i1%> src <%=$x%> table 192.168.0_RT
ip route add default via 192.168.0.1   dev <%=$i1%>        table 192.168.0_RT

ip route add <%= $c_to_n2 %>/<%= $cidr %> dev <%=$i2%> src <%=$y%> table 192.168.168_RT
ip route add default via 192.168.168.1   dev <%=$i2%>          table 192.168.168_RT
ip rule add from <%= $x %>/32   table 192.168.0_RT
ip rule add from <%= $y %>/32 table 192.168.168_RT

就目前而言,代码正在按预期工作,但是,如果我在if / else之间放置行(ip route ...),则所有内容均打印在同一行上,而没有换行符。 所以主要的问题是如何使代码看起来更简洁:)

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么要在if块之间呈现这些行,您需要添加html换行符
标记,然后将字符串标记为#html_safe或在视图中使用“ #h”帮助器。

例如:

<% (1..4).each do |i| %>
  <% if i.even? %>
    <%= h "#{i} is even<br>" %>
  <% else %>
    <%= h "#{i} id odd<br>" %>
  <% end %>
<% end %>

应该创建HTML呈现这样的:

1 is odd
2 is even
3 is odd
4 is even