ruby - 使用绑定(bind)递归调用 ERB 会导致输出文本丢失

标签 ruby binding erb templating

(注意:我使用的是 Ruby 的 erb,而不是 Rails 的。)
当使用当前绑定(bind)从另一个 ERB 模板中解析 ERB 模板时,在调用内部模板之前的外部模板的文本会丢失。
例如:inner.erb文件内容:

inner
outer.erb文件内容:
outer
<%= ERB.new(File.read('inner.erb')).result(binding) %>
outer
测试脚本erb-test (必须做 chmod +x erb-test ):
#!/usr/bin/env ruby

require 'erb'

puts ERB.new(File.read('outer.erb')).result
./erb-test 的输出是:
inner

outer
如图所示,outer.erb 中指定的第一个“外部”字符串模板文件丢失。
如果我们删除 binding来自 outer.erb 中的 ERB 调用:
<%= ERB.new(File.read('inner.erb')).result %>
...然后我们现在看到第一个 outer在外部模板中指定:
outer
inner

outer
这是一个错误吗?你建议如何解决这个问题?我意识到最好限制模板可用的状态,通常我会使用 ERB#result_with_hash ,但是在子模板的情况下,即从另一个模板调用的模板,在我看来,内部模板继承外部模板的绑定(bind)似乎是合理的,因为它已经被限制了。

最佳答案

这可以通过使用 eoutvar parameter to ERB.new 来解决。 , 如下:

<%= ERB.new(File.read('inner.erb'), eoutvar: '@inner').result(binding) %>
ERB 源代码中的注释进一步解释了它:
# _eoutvar_ can be used to set the name of the variable ERB will build up
# its output in.  This is useful when you need to run multiple ERB
# templates through the same binding and/or when you want to control where
# output ends up.  Pass the name of the variable to be used inside a String.
更改outer.erb的内容后到:
outer
<%= ERB.new(File.read('inner.erb'), eoutvar: '@inner').result(binding) %>
outer
...结果是:
outer

inner

outer
请注意,如果您在构造函数调用中传递未命名的参数,则需要使用命名方法,例如对于修剪模式:
    ERB.new(File.read(erb_filespec), eoutvar: eoutvar, trim_mode: '-')
代替:
    template = ERB.new(File.read(erb_filespec), 0, '-')

关于ruby - 使用绑定(bind)递归调用 ERB 会导致输出文本丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65444323/

相关文章:

ruby - 如何使用 Thor 模板在作用域内创建 ruby​​ 变量和方法?

javascript - 如何防止将具有数字内容的字符串插值为 ERb 中 JavaScript 的数字表达式

ruby-on-rails - Rails 4,Turbolinks 3,部分替换

ruby-on-rails - 使用渲染后表单不起作用

ruby - 将时间序列值的 Ruby 数组映射到加权间隔

c# - 具有两种方式数据绑定(bind)的 Winforms 文本框无法正常工作

jQuery 可拖动列表,其中包含可单击对象 - 防止单击拖动

ruby-on-rails - 重构 Rspec 规范

WPF : Binding cannot find source

ruby - Puppet:迭代模板中的 hiera_hash