Is there a way to list the available variables in an Ruby ERB template?

前端 未结 1 1642
终归单人心
终归单人心 2020-12-20 18:56

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

<%= @div_1 %>
<
相关标签:
1条回答
  • 2020-12-20 19:23

    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
    
    0 讨论(0)
提交回复
热议问题