Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lunks/a3d5d7fbb46385a91f51 to your computer and use it in GitHub Desktop.
Save lunks/a3d5d7fbb46385a91f51 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 updated to Sprockets 3 + other changes

Updates:

  • Sprockets 3 doesn't seem to need me to inject JavascriptHelpers.
  • Using environment[file].to_s to fetch the compiled sources.
  • Everything in my app (templates and scripts) is inside an app/ folder which is my angular app, so I leave that path part out on the $templateCache key
  • I'm only supporting slim templates because I only use slim, but it should fairly easy to add other template engines.
  • The previous script broke on files like course-link.directive.slim. We just remove the .slim extension now.
//= require angular
//= require angular-animate
//= require angular-resource
//= require_tree ./app
# app/assets/javascript/app/bootstrap.js.coffee
@myApp = angular.module('app', ['ngResource', 'app.templates'])
# config/initializers/slim_assets.rb
Rails.application.assets.register_engine('.slim', Slim::Template)
<%# app/assets/javascript/app/templates %>
angular.module('app.templates', []).run([ '$templateCache', function($templateCache) {
<%
app_root = File.expand_path('../', __FILE__)
templates = File.join(app_root, %w{** *.slim})
Dir.glob(templates).each do |f|
depend_on(f)
key = f.gsub(%r(^#{app_root}/),'').gsub(/\.slim/, '')
content = environment["app/#{key}.html"].to_s
%>
$templateCache.put("<%= key %>", "<%= escape_javascript(content) %>" );
<% end %>
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment