开发者

Rails accessing a view partial via the browser url

开发者 https://www.devze.com 2022-12-20 17:24 出处:网络
I\'ve got some javascript that needs to load a rails partial - I\'d prefer not to repeat the partial\'s HTML in the javascript file.

I've got some javascript that needs to load a rails partial - I'd prefer not to repeat the partial's HTML in the javascript file.

Is there a way to make this partial accessible via the browser url so JS can load it?

partial location:

shared/_search.html.erb

I would like to grab the view html with something like this:

example.com/shared/search.html
开发者_运维问答

Can I explicitly route this or grab it locally via the file system?

I don't want to have to create a controller just to render this partial for the JS.


You don't need to create a new controller file. But you do need an action to respond to the incoming request from your JS.

That action can render a partial specifically if you want. You can also generalize the action by having the JS ask for the partial by name as one of the parameters to the action.

If the issue is that you need to rapidly service a zillion of these calls coming in and you don't need the ActiveController machinery (you don't want to create a controller instance for the request), you could use Rails Metal -- http://railscasts.com/episodes/150-rails-metal

Added: Another option is to store a template file on your server (in public/assets etc). Then:

  1. JS retrieves template once per page load
  2. JS makes call to rails with params, to retrieve just the response (no markup)
  3. JS, locally on the browser, merges the response into the template. Either step by step or by using a JS lib such as Jaml
  4. Repeat steps 2-3 ad infinitum


As mentioned above, you will still need to create an action in a controller. Controllers are always required to map an incoming request in Rails.

The render method contains a range of options for presenting content - you can load a file directly, or even generate inline text to return as the result of the action call.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号