简体   繁体   中英

Ajax Load Static Rails Partial

In my rails app, I have a html template located in 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 .

// 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)

Quick answer/related SO answer: Rendering partial in js.erb file

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.

I would decouple the JS and create an internal endpoint in 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:

$.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.

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