有没有办法列出Ruby ERB模板中的可用变量? [英] Is there a way to list the available variables in an Ruby ERB template?

查看:79
本文介绍了有没有办法列出Ruby ERB模板中的可用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如,以下方法:

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']

任何帮助将不胜感激

谢谢,
Mike

Thanks, Mike

推荐答案

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

在erb中添加断点:

<% debugger %>

然后输入实例变量以查看所有可用的实例变量。

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

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

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.

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

这篇关于有没有办法列出Ruby ERB模板中的可用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆