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

发布于 2024-09-25 04:21:35 字数 581 浏览 1 评论 0原文

假设我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北音执念 2024-10-02 04:21:35

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

在 erb 中添加断点:

<% debugger %>

然后输入 instance_variables 在调试器中查看所有可用的实例变量。

添加:请注意 instance_variables 是 Ruby 类 Object 中可用的方法,并且它的所有子类。 (正如 @mikezter 所指出的。)因此,如果您确实愿意,可以从软件中以编程方式调用该方法,而不是使用调试器。

您将获得当前对象的实例变量列表。

添加:获取 .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

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

Add a breakpoint in the erb:

<% debugger %>

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:

# <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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文