有没有办法列出Ruby ERB模板中的可用变量?

时间:2021-11-05 22:30:17

Suppose I have a Ruby ERB template named my_template.html.erb, and it contains the following:

假设我有一个名为my_template.html.erb的Ruby ERB模板,它包含以下内容:

<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

1 个解决方案

#1


23  

To get a list of variables available to your .erb file (from the controller):

要获取.erb文件可用的变量列表(来自控制器):

Add a breakpoint in the erb:

在erb中添加断点:

<% debugger %>

Then type instance_variables in the debugger to see all of the available instance variables.

然后在调试器中键入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.

补充:请注意,instance_variables是Ruby类Object及其所有子类中可用的方法。 (正如@mikezter所指出的那样。)因此,您可以从sw中以编程方式调用该方法,而不是使用调试器,如果您真的想要。

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:

补充:要获取.erb文件使用的变量列表:

# <template> is loaded with the entire contents of the .erb file as
# one long string
var_array = template.scan(/(\@[a-z]+[0-9a-z]*)/i).uniq

#1


23  

To get a list of variables available to your .erb file (from the controller):

要获取.erb文件可用的变量列表(来自控制器):

Add a breakpoint in the erb:

在erb中添加断点:

<% debugger %>

Then type instance_variables in the debugger to see all of the available instance variables.

然后在调试器中键入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.

补充:请注意,instance_variables是Ruby类Object及其所有子类中可用的方法。 (正如@mikezter所指出的那样。)因此,您可以从sw中以编程方式调用该方法,而不是使用调试器,如果您真的想要。

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:

补充:要获取.erb文件使用的变量列表:

# <template> is loaded with the entire contents of the .erb file as
# one long string
var_array = template.scan(/(\@[a-z]+[0-9a-z]*)/i).uniq