简体   繁体   中英

How to pass a partial html.erb form from js.erb file instead of just a message?

I am trying to implement jquery on a sample ruby on rails app. I just started to explore the js. I know I have so much to learn in js/jquery. Right now there is something I am stuck with.

I have a js.erb file as follows:

js.erb

<% if @phone_number.verified %>
  $('#verify-pin').hide()
  $('#status-box').removeClass()
  $('#status-box').addClass('alert alert-success')
  $('#status-message').text('Verified!!')
<% else %>
  $('#status-box').removeClass()
  $('#status-box').addClass('alert alert-warning')
  $('#status-message').text("Sorry, that wasn't the right pin.")
<% end %>
$('#status-box').fadeToggle()

If you see the 5th line, right now I am just flashing a text message "Verified!!" when the the condition is true. But instead I want display a partial erb form. I have a _form.html.erb file. How can I display this instead of a text message?

You use the escape_javascript method.

$('#status-message').html("<%= escape_javascript(render 'form) %>");

It is also aliased as just j

$('#status-message').html("<%= j(render 'form) %>");

Obviously you might want to do some more fancy stuff with this, but this is the basic idea.

While you do have .js.erb and could use erb directly in your JS, I want to show a workaround that'll work for those without .js.erb (eg with .coffee formats) and that will work for all build stacks.

In your application.html.erb, add a script tag and initiate a global variable, then you can use that variable to append a partial whenever you might need the partial. Like this:

<script>
    partials = {
        foobarPartial: '<%= escape_javascript(render partial: 'foobar', :locals => { :local_var_1 => false, :local_var_2 => 'foo' }) %>'
    };
</script>

Then, whenever you need that partial, just add it via .html(partials.foobarPartial)

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