Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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/
@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|
key = f.gsub(%r(^#{app_root}/templates/),'').split('.').first
content = environment.find_asset(f).body
$templateCache.put("<%= key %>", "<%= escape_javascript(content) %>" );
<% end %>

This comment has been minimized.

Copy link

assembler commented Aug 31, 2015

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 =

This comment has been minimized.

Copy link

eric-simonton-sama commented Sep 29, 2015

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, as assembler suggested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.