You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮用CoffeeScript渲染Rails局部视图时出现字面量输出问题

问题原因与解决方案

你遇到的问题核心是:Rails不会自动解析.js.coffee文件里的ERB标签,因为这个文件没有被标记为需要ERB预处理,所以里面的<%= j render('repeticions/form') %>会被当作普通字符串直接输出到浏览器,而不是被服务器渲染成局部视图的HTML。

下面给你两种可行的解决方法:

方法一:修改文件名启用ERB预处理

最简单的方式是把你的CoffeeScript文件重命名为script.js.coffee.erb——添加.erb后缀后,Rails会先执行文件里的ERB代码,再编译CoffeeScript。

修改后的代码如下:

$('[id^="btn_add_rep_dia_"]').click ->
  id = this.id.substring(16)
  # 用反引号包裹ERB输出,避免CoffeeScript的字符串语法冲突
  $("#dia" + id).append(`<%= j render('repeticions/form') %>`)

这里用反引号(`)是因为escape_javascript(简写为j)会转义HTML里的换行和引号,反引号在CoffeeScript中支持多行字符串,能避免语法错误。

方法二:用AJAX动态请求局部视图

如果后续需要更灵活的动态加载(比如传递参数到局部视图),推荐用AJAX方式,把局部视图的渲染逻辑放在服务器端:

  1. 添加控制器动作
    在你的RepeticionsController里新增一个动作,专门返回局部视图:
def new_form
  # 可以在这里初始化需要的实例变量,比如@repeticion = Repeticion.new
  render partial: 'repeticions/form', layout: false
end
  1. 配置路由
    在config/routes.rb里添加对应的路由:
get 'repeticions/new_form', to: 'repeticions#new_form'
  1. 修改CoffeeScript代码
    用jQuery的$.get请求服务器获取渲染好的HTML,再添加到页面中:
$('[id^="btn_add_rep_dia_"]').click ->
  id = this.id.substring(16)
  $.get '/repeticions/new_form', (rendered_html) ->
    $("#dia" + id).append(rendered_html)

如果需要传递参数(比如关联的dia_id),可以这样修改:

$('[id^="btn_add_rep_dia_"]').click ->
  id = this.id.substring(16)
  $.get '/repeticions/new_form', { dia_id: id }, (rendered_html) ->
    $("#dia" + id).append(rendered_html)

然后在控制器动作里就能通过params[:dia_id]拿到这个参数,用来初始化关联对象。

内容的提问来源于stack exchange,提问作者Josemafuen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:38:35