Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Last active April 30, 2016 23:20
Show Gist options
  • Save stevenharman/8493700 to your computer and use it in GitHub Desktop.
Save stevenharman/8493700 to your computer and use it in GitHub Desktop.
Load the Angular.js $templateCache while building assets for Rails Asset Pipeline. Be sure in require the `templates` module as a dependency of your Angular.js app.

AngularJS + Rails Asset Pipeline

This is my hand-rolled solution for getting Angular assets (Controllers, Models, Directives, Templates, etc.) integrated into the Rails Asset Pipeline.

Templates and the $templateCache

Of particular note: this hack will also load the AngularJS $templateCache with your templates, while allowing you to use Slim, ERB, etc. to write your templates.

//= require angular
//= require angular-animate
//= require angular-resource
//
//= require ./my_app/bootstrap
//= require ./my_app/templates
//= require_tree ./my_app/controllers
//= require_tree ./my_app/directives
//= require_tree ./my_app/models
# app/assets/javascript/my_app/bootstrap.js.coffee
@myApp = angular.module('myApp', ['ngResource', 'templates'])
# config/initializers/slim_assets.rb
Rails.application.assets.register_engine('.slim', Slim::Template)
<%# app/assets/javascript/my_app/templates %>
angular.module('templates', []).run([ '$templateCache', function($templateCache) {
<%
environment.context_class.instance_eval { include ActionView::Helpers::JavaScriptHelper }
app_root = File.expand_path('../', __FILE__)
templates = File.join(app_root, %w{templates ** *})
Dir.glob(templates).each do |f|
depend_on(f)
key = f.gsub(%r(^#{app_root}/templates/),'').split('.').first
content = environment.find_asset(f).body
%>
$templateCache.put("<%= key %>", "<%= escape_javascript(content) %>" );
<% end %>
}]);
@assembler
Copy link

line #11 on sprockets 3+ should be:

content = environment.find_asset(f).source

However, it doesn't return the compiled template, but the original one. I've ended up doing it like this:

content = Tilt.new(f).render

@eric-simonton-sama
Copy link

Thank you steveharmam, and thank you assembler.

I learned the hard way that environment.find_asset(f).source works just fine in development, but don't be fooled! In production I had to use Tilt.new(f).render, as assembler suggested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment