简体   繁体   English

Ajax 加载静态 Rails 部分

[英]Ajax Load Static Rails Partial

In my rails app, I have a html template located in public/templates/_hero-1.html.erb在我的 rails 应用程序中,我有一个 html 模板位于public/templates/_hero-1.html.erb

In my application.js.erb file, I'm trying to load that template into a div I created dynamically, before I render the entire div .在我application.js.erb文件,我想该模板加载到div我动态创建的,之前我渲染整个div

// Append component to text editor when clicked
$('.js-TemplateThumbnail').click(function() {
    // Define new template container
    var newTemplateContainer = $('<div class="position-relative hideChild js-TemplateContainer">');

    // Insert selected template into new template container
    newTemplateContainer.load("<%= 'public/templates/hero-1' %>");

    // Build new template
    $('.js-Canvas .js-TemplateContainer').last().after(newTemplateContainer);
});

But I'm getting a console error GET http://localhost:3000/public/templates/hero-1 404 (Not Found)但我收到控制台错误GET http://localhost:3000/public/templates/hero-1 404 (Not Found)

Quick answer/related SO answer: Rendering partial in js.erb file快速答案/相关 SO 答案: 在 js.erb 文件中渲染部分

Longer answer: There are a couple ways of doing this.更长的答案:有几种方法可以做到这一点。 You could try:你可以试试:

newTemplateContainer.load("<%= 'render partial: public/templates/hero-1' %>");

Not positive that will work.不是积极的,会起作用。 This feels hacky to me and also leaves you with highly coupled code.这对我来说感觉很糟糕,并且还会给您留下高度耦合的代码。 If the name of that template changes, you will have to update it in n places.如果该模板的名称发生更改,则必须在 n 个位置更新它。

I would decouple the JS and create an internal endpoint in config/routes.rb ;我会解耦 JS 并在config/routes.rb创建一个内部端点; eg:例如:

get templates/:id

then,然后,

class TemplatesController < ApplicationController
  def show
    @template = Template.find(params[:id])
  end   
end

Then in your JS inside the click handler you can:然后在单击处理程序内的 JS 中,您可以:

$.get('/templates/hero-1', function(data) {
   // do stuff with returned data
   $('.js-Canvas').html(data)
});

Very simplistic, but more so trying to outline a different approach.非常简单,但更多的是试图概述一种不同的方法。 This also seems like something that handlebars could help with.这似乎也是车把可以提供帮助的东西。

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

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