有没有办法列出 Ruby ERB 模板中的可用变量?
假设我有一个名为 my_template.html.erb 的 Ruby ERB 模板,并且它包含以下内容:
<div><%= @div_1 %></div>
<div><%= @div_2 %></div>
<div><%= @div_3 %></div>
有没有一种方法可以以编程方式列出模板中的所有可用变量?
例如,以下方法:
def list_out_variables
template = File.open("path_to/my_template.html.erb", "rb").read
erb = ERB.new( template )
erb.this_method_would_list_out_variables
end
将返回类似以下内容:
['div1','div2','div3']
任何帮助将不胜感激。
谢谢, 麦克风
Suppose I have a Ruby ERB template named my_template.html.erb, and it contains the following:
<div><%= @div_1 %></div>
<div><%= @div_2 %></div>
<div><%= @div_3 %></div>
Is there a way I can programatically list out all the available variables in the template?
For example, the following method:
def list_out_variables
template = File.open("path_to/my_template.html.erb", "rb").read
erb = ERB.new( template )
erb.this_method_would_list_out_variables
end
would return something like:
['div1','div2','div3']
Any help would be greatly appreciated.
Thanks,
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获取 .erb 文件可用的变量列表(从控制器):
在 erb 中添加断点:
然后输入 instance_variables 在调试器中查看所有可用的实例变量。
添加:请注意 instance_variables 是 Ruby 类 Object 中可用的方法,并且它的所有子类。 (正如 @mikezter 所指出的。)因此,如果您确实愿意,可以从软件中以编程方式调用该方法,而不是使用调试器。
您将获得当前对象的实例变量列表。
添加:获取 .erb 文件使用的变量列表:
To get a list of variables available to your .erb file (from the controller):
Add a breakpoint in the erb:
Then type instance_variables in the debugger to see all of the available instance variables.
Added: Note that instance_variables is a method available from the Ruby class Object and all of its subclasses. (As noted by @mikezter.) So you could call the method programmatically from within your sw rather than using the debugger if you really wanted to.
You'll get back a list of instance variables for the current object.
Added: To get a list of the variables used by an .erb file: