Rendering HAML partials from within HAML outside of Rails

前端 未结 5 612
后悔当初
后悔当初 2020-12-31 16:54

I\'m using HAML to generate some static html pages for a site, and I was wanting to split out common components into partials that I can include in multiple pages, just like

5条回答
  •  情书的邮戳
    2020-12-31 17:24

    I had the same problem. I needed to generate some html snippets to optimize the server response, once this snippets have a lot of calculations(for drawing graphs) and every time a user do a request it was doing all the stuff unnecessarily.

    Once i have the views partitioned in several haml partials, i wanted to reuse this to generate the html files.

    My first approach was trying with the Haml engine, but once i have partials rendering other partials and some functions of the application helper, it didn't worked. Finality i found a solution that passed by creating a function in the models that i wanted to create an html file ( to_html ) Here is it:

    def to_html
      ActionView::Base.send :include, ActionView::Helpers::ApplicationHelper
    
      File.open(File.join(Rails.root, "public", 'test.html'), "w") do |file|
    
      file.print ActionView::Base.new(Rails.configuration.paths["app/views"].first).render(
                    :partial => 'partial_folder/partial', 
                    :format => :html,
                    :locals => { :model => self}
                  )
      end  
    end
    

    This way, i was able to use the already done partials, to print the html files. This worked for me, maybe it can help you also.

提交回复
热议问题