英文:
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("1. <%= ERB.new('2').result binding %>. 3").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("1. <%= ERB.new('2', eoutvar: \"_erbout2\").result binding %>. 3").result binding
#=> "1. 2. 3"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论