Mik*_*e G 7 ruby ruby-on-rails erb
假设我有一个名为my_template.html.erb的Ruby ERB模板,它包含以下内容:
<div><%= @div_1 %></div>
<div><%= @div_2 %></div>
<div><%= @div_3 %></div>
Run Code Online (Sandbox Code Playgroud)
有没有办法可以编程方式列出模板中的所有可用变量?
例如,以下方法:
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
Run Code Online (Sandbox Code Playgroud)
会返回类似的东西:
['div1','div2','div3']
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
谢谢,迈克
Lar*_*y K 25
要获取.erb文件(来自控制器)可用的变量列表:
在erb中添加断点:
<% debugger %>
Run Code Online (Sandbox Code Playgroud)
然后在调试器中键入instance_variables以查看所有可用的实例变量.
补充:请注意,instance_variables是Ruby类Object及其所有子类中可用的方法.(正如@mikezter所指出的那样.)因此,如果您真的想要,可以从sw中以编程方式调用该方法,而不是使用调试器.
您将获得当前对象的实例变量列表.
补充:要获取.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6321 次 |
| 最近记录: |