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)

1
  • 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. Commented Oct 12, 2016 at 3:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
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.
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.
I just want to house them in a folder somewhere like that, then load the relevant one inside the dynamically built <div>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.