简体   繁体   中英

Rails Layout for JS and HTML rendering

Okay, so this might be kind of strange but here's the question:

I have a great number of similar controller/view interactions that I'd like to make more DRY. The user clicks a link, which is converted to perform an AJAX response with JQuery. The response expects some JavaScript to be returned and executed. Several of these follow the same pattern:

$("working_div").html("<%= render partial => 'some_partial' %>")

Is there a way to make it so that I can DRY this up by doing...

$("working_div").html("<%= yield %>")

And it still return JavaScript?

Yes, you can, if you use layouts within layouts. (It requires you to build one more file, but it will be DRY.) I'm not sure if this is what you want, but here's how it works.

Your nested layout can call yield (even if you have an ordinary layout which also calls yield . For js, your render stack will proceed: [template] > [partial layout] > [partial]

Your controller will call your ordinary render command (or none, if it's implicit). (I don't know where you want to declare which partial is to be rendered, so I just picked here.):

def index
  @partial = params[:partial] || 'some_partial'
  respond_to do |format|
    format.js render :template => 'my_template'
  end
end

Your template, instead of calling the partial ( some_partial ) will call a partial template, which in turn calls the partial:

# my_template
/* Some js ... */
$("#working_div").html("<%= render :layout => "nested_layout", :partial => @partial %>")
/* Some more js ... */

Your nested partial can then call the method yield :

# nested_partial
/* Some js ... */
<%= yield %>
/* Some more js ... */

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