Ruby 模板化:是否可以只将一些值传递给模板中的变量?

Ruby templating: is it possible that only pass some values to variables in template?

我正在学习 ruby 模板并查看 ruby 文档提供的示例。

require 'erb'
x = 42
template = ERB.new <<-EOF
   The value of x is: <%= x %>
EOF
puts template.result(binding)

当我通过执行以下操作更改示例时:

require 'erb'
x = 42
template = ERB.new <<-EOF
   The value of x is: <%= x %>
   The value of y is <%= y %>
EOF
puts template.result(binding)

我希望模板会变成这样:

The value of x is: 42
The value of y is <%= y %>

它给我错误:

Error: undefined local variable or method `y' for main:Object (NameError)

看来我们需要传递模板中所有变量替换的所有值。

问题: 我只是想知道是否有可能我们可以在模板中进行两个变量替换,但在绑定数据时只将一个值传递给模板?

可以使用双开%%s来防止在erb中被求值

这个解决方案可能看起来很丑陋,但它returns正是您想要的(如果它是您想要的):

require 'erb'

template = ERB.new <<-EOF
  The value of x is: <% if defined?(x) %><%= x %><% else %><%%= x %><% end %>
  The value of y is: <% if defined?(y) %><%= y %><% else %><%%= y %><% end %>
EOF
 => #<ERB:0x00007feeec80c428 @safe_level=nil, @src="#coding:UTF-8\n_erbout = +''; _erbout.<<(-\"  The value of x is: \");  if defined?(x) ; _erbout.<<(( x ).to_s);  else ; _erbout.<<(-\"<%= x %>\");  end ; _erbout.<<(-\"\n  The value of y is: \"\n);  if defined?(y) ; _erbout.<<(( y ).to_s);  else ; _erbout.<<(-\"<%= y %>\");  end ; _erbout.<<(-\"\n\"\n); _erbout", @encoding=#<Encoding:UTF-8>, @frozen_string=nil, @filename=nil, @lineno=0> 

puts template.result(binding)
  The value of x is: <%= x %>
  The value of y is: <%= y %>
 => nil 

x = 20

puts template.result(binding)
  The value of x is: 20
  The value of y is: <%= y %>
 => nil 

y= 50

puts template.result(binding)
  The value of x is: 20
  The value of y is: 50
 => nil 

我假设你可以进行格式化。