Bright loading of HTML / erb templates in Rails for AngularJS

I follow the flow of http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading for loading HAML templates. It seems like a sensible way to provide Angular has all the partial HTML parts that it should cache at boot time to avoid unnecessary round trips to the server. My question is: how to do the same thing with regular erb / HTML templates if we do not use HAML? On this particular line:

$templateCache.put("<%= File.basename(f).gsub(/\.haml$/, '') %>", <%= Haml::Engine.new(File.read(f)).render.to_json %>); <% end %> 

Erb templates will need something else for Haml::Engine.new . Is there a solution for this, so that I can implement the above for my non-Haml based templates?

+7
javascript angularjs ruby ruby-on-rails erb
source share
2 answers

Source code using HAML:

 <% Dir.glob(Rails.root.join('app','assets','templates', '*.haml')).each do |f| %> $templateCache.put("<%= File.basename(f).gsub(/\.haml$/, '') %>", <%= Haml::Engine.new(File.read(f)).render.to_json %>); <% end %> 

To select all ERB templates, use

 Dir.glob(Rails.root.join('app', 'assets', 'templates', '*.erb')) # => ['a.erb', 'b.erb', ...] 

To get the template name from the file name, use

 File.basename(f, '.erb') 

To make an ERB template, use

 ERB.new(File.read(f)).result 

See the documentation for #result .

Putting it all together, we get

 <% Dir.glob(Rails.root.join('app','assets','templates', '*.erb')).each do |f| %> $templateCache.put("<%= File.basename(f, '.erb') %>", <%= ERB.new(File.read(f)).result.to_json %>); <% end %> 
+7
source share

For ERB templates, you can use:

 <% Dir.glob(Rails.root.join('app','assets','templates', '*.erb')).each do |f| %> $templateCache.put("<%= File.basename(f).gsub(/\.erb$/, '') %>", <%= ERB.new(File.read(f)).result.to_json %>); <% end %> 
+3
source share

All Articles