简体   繁体   中英

Rails 3 Render a partial in a JS file

I have a Rails 3 application that is serving a js file eg, tools.js.erb via the assets pipeline. This is working fine, but I want to add some html templates which are available as partials within the environment.

One option was to load the template via an ajax call from the JS when the template is required, but that would add some delay in presenting it on the client.

Is it possible to render a partial inside the JS and store it in a JS variable as a string, so I can just inject the html right away. What is the best way to do this?

Yeah, you can do something like this:

var container = $("#your_container");
var myPartial = "<%= j render( :partial => 'directory/your_partial' ) %>";

// on.click, or whatever...
container.prepend(myPartial);

Not sure if you want to prepend or replace the HTML, but this should get you on the right track. Good call saving the markup for the partial in a Javascript variable. Should speed things up.

It HTML you want to add/update requires some variables, you would have to make a server trip anyways and would have reload your dom. Otherwise if it is a static content, you can follow this approach. Just create one variable in your action like this.

@my_view_content = render_to_string partial: 'path_to_partial', formats: ['html'], layout: false, object: something

Now, you can use this variable or pass this variable to your JS file.

var my_view_content_string = = "#{@my_view_content}"

Why do you want to store a view in a variable if you have few good options.. why cant you use a conditon ..such as in show.js.erb

<% if condition %>

  $('#div1').html("<%= escape_javascript(render(:partial => 'pages/show')) %>");

<%else%>

  $('#div1').html("<%= escape_javascript(render(:partial => 'users/show')) %>");

<%end%>

ELSE THIS IS OTHER WAY TO DO IT....

###check of a condition in your view and then add element and call ajax

   <%if current_user.sign_in_count == 1 && current_user.confirmed?  %>
            <%= hidden_field(:new_user, :first_login, :value => current_user.sign_in_count)%>
  <%end%>    



  <script type="text/javascript">
$(document).ready(function() {
 //check if element is present in the dom and then call ajax
  if ($('#new_user_first_login').length) {
        $.ajax({
          //CALL AJAX
        })

  }
  })//document ends​
 </script>

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