简体   繁体   中英

call .js.erb file instead of .html.erb

I have Rails application with a google map. I want to populate it with markers using a .js.erb file so that I have access to ruby variables in javascript. I don't want to use gon gem.

Is there a way to have the action call .js.erb file instead of the .html.erb file?

One way around this is to load the .html.erb and then have to do an automatic ajax call to load the .js.erb, but I'm looking for a better solution.

Thanks.

The controller really isn't the right way to that, since its job is to respond to requests. If a request comes in and expects to get HTML back, Rails will give HTML back. If it's a JS request, it sends JS back.

The right way to do this is to load the page with HTML and then do an AJAX call from the page. You can even send it to the same action and Rails will respond with the appropriate js.erb template. If you want to give it special instructions, maybe if you want your JSON rendered in a specific way, you can do that with respond_to or the JBuilder gem.

Edit: The above is written under the assumption that you are loading the page through a normal HTML request and you want it to do both HTML and JS. If you are already on a page and you want to do an AJAX call through a link, button, or form without rendering HTML at all, you can do that by adding remote: true to any form_for , form_tag , button_to , or link_to tags.

If you want to avoid a second call and have no expectation that your controller will need to respond with JSON, you can put the data you're looking for into HTML5 data attributes right in your view. Those exist specifically for the purpose of providing information to JS. You can just do one with its value set to an array containing your markers, then have your script run through each element of that array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM