Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager load HTML/erb templates in Rails for AngularJS

I'm following the thread on http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading for eager loading HAML templates. Seems like it's a reasonable way of ensuring Angular has all the HTML partials it needs cached on initial load to avoid unnecessary round trips to the server. My question is, how does one 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 %>

One would need whatever the substitute is for Haml::Engine.new for erb templates. Is there a solution for that offhand so I can implement the above for my non-Haml based templates?

like image 552
randombits Avatar asked Aug 05 '13 14:08

randombits


2 Answers

The original code using HAML is:

<% 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 a file name, use

File.basename(f, '.erb')

To render an ERB template, use

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

Refer to the documentation for #result.

Putting everything 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 %>
like image 197
James Lim Avatar answered Nov 14 '22 05:11

James Lim


For ERB templates you might 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 %>
like image 39
XLII Avatar answered Nov 14 '22 05:11

XLII