在 js.erb 文件中渲染部分 [英] Rendering partial in js.erb file

查看:36
本文介绍了在 js.erb 文件中渲染部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于 ajax 的评论表单,它将在提交时更新我的​​评论列表.非常基本的东西.

我有一个部分 comments/_single.html.haml,它有一个带有基本评论信息的

  • 标签,这是我的 comments/create.js.erb 文件(实际上这是将三个不同的测试文件合并为一个以显示我的问题所在):

    $('#comments ul.comments').append("<%= render :partial => 'comments/single', :locals => { :c => @comment }%>");$('#comments ul.comments').append("<%= render :partial => 'comments/foobar' %>");$('#comments ul.comments').append("foobar");警报('foobar');

    comments/_foobar.html.haml 的内容只是foobar,里面没有html.我的问题是前两行不起作用.我的开发服务器控制台中没有错误,对象检查器说正确返回了评论代码,但它们没有添加到我的评论列表中.第三行工作正常,所以第四行.看起来使用 render 存在一些问题.

    解决方案

    在Javascript代码中渲染partials时,应该使用escape_javascript方法,就像这样

    $('#comments ul.comments').append("<%= escape_javascript render(:partial => 'comments/single', :locals => { :c => @评论 }) %>");

    这个方法别名为j,所以你也可以这样做

    $('#comments ul.comments').append("<%= j render(:partial => 'comments/foobar') %>");

    <块引用>

    JavaScript 段的转义回车和单引号和双引号的方法ActionView::Helpers::JavaScriptHelper Rails 文档

    I'm trying to create an ajax-based comment form which will update my comments list when submitted. Pretty basic stuff.

    I have a partial comments/_single.html.haml which has a single <li> tag with basic comment info and here is my comments/create.js.erb file (actually these are three different test files merged into one to show you what my problem is):

    $('#comments ul.comments').append("<%= render :partial => 'comments/single', :locals => { :c => @comment } %>");
    $('#comments ul.comments').append("<%= render :partial => 'comments/foobar' %>");
    $('#comments ul.comments').append("foobar");
    alert('foobar');
    

    The content for comments/_foobar.html.haml is just foobar, no html inside. My problem is that first two lines doesn't work. There are no errors in my dev server console, object inspector says that comment code was returned correctly but they are not added to my comments list. The third line works fine and so the fourth one. It looks like there are some problems with using render.

    解决方案

    When rendering partials inside Javascript code, you should use the escape_javascript method, like so

    $('#comments ul.comments').append("<%= escape_javascript render(:partial => 'comments/single', :locals => { :c => @comment }) %>");
    

    This method is aliased as j, so you can also do this

    $('#comments ul.comments').append("<%= j render(:partial => 'comments/foobar') %>");
    

    The method Escapes carriage returns and single and double quotes for JavaScript segments ActionView::Helpers::JavaScriptHelper Rails docs

    这篇关于在 js.erb 文件中渲染部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆