简体   繁体   English

如何从js.erb文件传递部分html.erb表单而不是仅传递消息?

[英]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. 我正在尝试在Rails应用程序的示例红宝石上实现jquery。 I just started to explore the js. 我刚刚开始探索js。 I know I have so much to learn in js/jquery. 我知道我在js / jquery中有很多东西要学习。 Right now there is something I am stuck with. 现在有一些我坚持的东西。

I have a js.erb file as follows: 我有一个js.erb文件,如下所示:

js.erb 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!!" 如果您看到第五行,那么现在我只是在闪烁一条文本消息“ Verified !!”。 when the the condition is true. 当条件为真时。 But instead I want display a partial erb form. 但是我想显示部分erb形式。 I have a _form.html.erb file. 我有一个_form.html.erb文件。 How can I display this instead of a text message? 如何显示此内容而不是短信?

You use the escape_javascript method. 您使用escape_javascript方法。

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

It is also aliased as just j 它也被别名为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. 虽然您确实有.js.erb并可以在JS中直接使用erb,但我想展示一种变通办法,该变通办法适用于那些没有.js.erb的人(例如,具有.coffee格式),并且适用于所有构建堆栈。

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. 在application.html.erb中,添加一个脚本标记并初始化一个全局变量,然后在需要时可以使用该变量附加部分。 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) 然后,每当需要该部分时,只需通过.html(partials.foobarPartial)添加它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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