1

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)

colmtuite
  • 4,311
  • 11
  • 45
  • 67
  • You will need to load it from the webserver....So you need to provide a route and a dedicated action to do the same using partial. – Milind Oct 12 '16 at 03:56

1 Answers1

1

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.

Community
  • 1
  • 1
cpk
  • 809
  • 1
  • 6
  • 20
  • 1
    Thanks man! Bear in mind, I will have hundreds of these templates and they're not individual pages, they're just tiny templates that form a page. So that's why I was hoping to avoid controllers etc. – colmtuite Oct 12 '16 at 04:36
  • It will be hard to avoid controllers in Rails! ;) Or any MVC framework for that matter. I'm guess I'm not sure 100% what you're trying to accomplish. – cpk Oct 12 '16 at 04:38
  • It would make sense to build one template even in erb and then pass the relevant data to that template from the controller so you don't actually create `hero-1....hero-100` etc. – cpk Oct 12 '16 at 04:40
  • Here are some of the templates https://github.com/colmtuite/bantam/tree/master/templates – colmtuite Oct 12 '16 at 04:51
  • I just want to house them in a folder somewhere like that, then load the relevant one inside the dynamically built
    .
    – colmtuite Oct 12 '16 at 04:52