ruby-on-rails – 将部分转换为方法/块以获得速度
我有一个循环,呈现部分
1000.times do |i| render partial: 'test',locals: {i: i} end 对于foreach渲染调用,这非常慢,最长可达0.1 ms,即使部分仅打印出i my_partial = render_to_method(partial: 'test') 1000.times do |i| my_partial(locals: {i: i}) end 现在这应该以更快的方式做同样的事情吧?但我不知道该怎么做. 更新: 我试过这样做: Haml::Engine.new(File.read(File.expand_path File.dirname(FILE)+"/../table/#{column.macro}/_#{column.display_type}.haml")) .??render(OpenStruct.new({column_value: column_value,object: object})) 两个主要缺点: >视图的路径不会像使用渲染时那样观察回退(parital:’partial’将在当前视图dir,某些宝石以及视图/应用程序中查找parital. 更新2: 许多答案试图通过使用其他技术来解决问题.我的真实应用这种技术无法应用. https://github.com/antpaw/bhf/blob/master/app/views/bhf/pages/_platform.haml#L54主要是因为这一行是一个动态字符串,有时会链接到甚至不存在于gem中的部分,并在main_app中定义.我想知道为什么做一些如此基本的事情是如此困难:1.抓住观点. 2.渲染它. (3.再次渲染.) 更新3: @Flash Gordon建议这是https://gist.github.com/antpaw/d6670c23d6f08e35812e#file-gistfile1-haml-L54 template = lookup_context.find_template "#{column.macro}/#{column.display_type}",['bhf/table'],true template.render(self,{column_value: column_value,object: object}) 它几乎与当地人有一些麻烦.但它已经感觉就像你抓住模板的部分,渲染部分是完全分开的. 解决方法
以下是我以前的一个答案的例子.它是从PartialRenderer源中提取的.
- local_names = [:i] - partials = {} - 1000.times do |i| - name = 'name_%s' % (i % 10) - partials[name] ||= lookup_context.find_template(name,lookup_context.prefixes,true,local_names) = partials[name].render(self,i: i) 我建议你用辅助方法包装它.请记住,locals的名称在这里出现两次:首先在local_names中作为数组,第二个在hash的键中作为#render方法的第二个参数传递. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |