如何在另一个erb调用中嵌套一个erb调用?

huangapple go评论71阅读模式
英文:

How to nest an erb call in another erb?

问题

运行以下代码:

ERB.new("1. <%= ERB.new('2').result binding %>. 3").result binding

输出结果应为:

1. 2. 3

看起来嵌套的 ERB 正确输出了预期的结果。nested erb 并不会删除模板中它之前的内容。如果你有其他问题或需要更多帮助,请随时提问。

英文:

When I run:

ERB.new(&quot;1. &lt;%= ERB.new(&#39;2&#39;).result binding %&gt;. 3&quot;).result binding

The output is:

2. 3

While the expected output is:

1. 2. 3

Seems like the nested erb is deleting everything before it in the template. Has anyone seen this before? What is the recommended way of nesting erbs? Is it possible?

答案1

得分: 1

在嵌套的ERB中存在命名空间冲突,特别是在 _erbout 变量方面,它会被重新初始化。

这种嵌套ERB的情况在 ERB.new()文档中有提到,文档指出,如果你在相同的作用域(binding)中操作,必须使用 :eoutvar 属性来重新命名这个变量。

ERB.new("1. <%= ERB.new('2', eoutvar: '_erbout2').result binding %>. 3").result binding
#=> "1. 2. 3"
英文:

There is a conflict in the namespace specifically in the _erbout variable which is reinitialized by the nested ERB.

This exact case of nesting ERBs is mentioned in the documentation of ERB.new() saying that the variable has to be renamed using :eoutvar attribute if you are operating in the same scope (binding).

ERB.new(&quot;1. &lt;%= ERB.new(&#39;2&#39;, eoutvar: \&quot;_erbout2\&quot;).result binding %&gt;. 3&quot;).result binding
#=&gt; &quot;1. 2. 3&quot;

huangapple
  • 本文由 发表于 2023年2月18日 07:48:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定