Joe Essey
Joe Essey

Reputation: 3527

How to insert a rails variable in to .js.erb span name?

I've got a .js.erb file that needs to replace a view's span based on the variable used in the associated controller. I can't figure out the proper notation to get the call to work. @i is assinged in the controller. Here's the .js.erb call:

$("span#remove_name_" + <%= @i %>).html("<%= escape_javascript(render(:partial => 'remove_position'))%>");

The name of the span I wish to replace is remove_name_42 for example.

Thanks.

Upvotes: 1

Views: 507

Answers (1)

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

I'll just talk about this part of the code: $("span#remove_name_" + <%= @i %>)

You must understand how files with double extensions work. In this case you have a file of type ".js.erb" that means your file will be interpreted by erb first, and the result will be a js file that will be interpreted by the browser. The 2 interpretations are done separately.

About the erb interpretation: try to keep in mind that it's just some kind of 'text processing'. If you try to figure out step by step what's append:

  1. Your code is $("span#remove_name_" + <%= @i %>)
  2. The @i value is 'example'
  3. erb replace this part of code <%= @i %> by the value if @i, which is 'example'
  4. the resulting js file will be: $("span#remove_name_" + example)

If your js code declared a variable named 'example' and the resulting code $("span#remove_name_" + example) is what you was expecting, then it's good.

But if your js code do not declare a 'example' variable, and your are expecting this code $("span#remove_name_example") because you are searching the span with id "remove_name_example" then this is how it must be done:

  1. Your code is $("span#remove_name_<%= @i %>")
  2. The @i value is 'example'
  3. erb replace this part of code <%= @i %> by the value if @i, which is 'example'
  4. the resulting js file will be: $("span#remove_name_example")

See how we removes the + and moved <%= @i %> inside the string? Once again think about 'text processing' and keep in mind that erb replace a variable by its value.

Upvotes: 2

Related Questions