繁体   English   中英

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

它给了我错误:

错误:main:Object(NameError)的未定义局部变量或方法“ y”

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

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

您可以使用两次打开%%来防止在erb中对其进行评估。

此解决方案可能看起来很丑陋,但它会精确返回您想要的内容(如果它是您想要的):

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 

我认为您可以进行格式化。

暂无
暂无

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

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