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?
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 %>
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With