2011-09-28 84 views
3

我有一個非常簡單的模板解析器從數據庫返回的模板:rails 3.1通過模板解析器模板特定的佈局?

class MyResolver < ActionView::PathResolver 
    def query path, details, formats 
    template = MyTemplate.find_by_path path 
    ... 
    ActionView::Template.new template.source, identifier, handler, details 
    end 
end 

這部分的偉大工程......我想不通的是如何告訴Rails使用與相關佈局從數據庫中拉出的模板(即,template.layout_name或其他)。

class MyResolver < ActionView::PathResolver 
    def query path, details, formats 
    template = MyTemplate.find_by_path path 
    layout template.layout_name # ??? yes? no? 
    ActionView::Template.new template.source, identifier, handler, details 
    end 
end 

有沒有什麼我可以調用上述查詢方法來設置佈局?我應該不是返回一個ActionView :: Template,而是返回帶有相應AV :: T方法的模板類,然後重寫渲染堆棧的其他部分,並使用template.layout_name?

+0

你有沒有找到一個工作解決方案?目前我做的和我在控制器中定義的任何佈局一樣,例如'layout「public」',將被忽略。所有渲染的都是視圖的內容 - 根本沒有佈局。 –

回答

2

你不得不做這樣的事情:

pages_controller.rb:

class PagesController < ApplicationController 

     prepend_view_path PageTemplate::Resolver.instance 

     def render_page 
     #Some logic to retrieve the @site & @current_page records.... 
     render :layout => @site.layout.path, :template => @current_page.template.path 
     end 
     . 
     . 
     . 

型號/ page_template.rb:

class Resolver < ActionView::Resolver 
    require "singleton" 
    include Singleton 

    def find_templates(name, prefix, partial, details) 
     if prefix.empty? 
      #If this is not a layout, look it up in the views table and pass that record to the init function 
      initialize_template('Template', record) 
     end 
     elsif prefix === 'layouts' 
     #If this is a layout, look it up in the layouts table and pass that record to the init function 
     initialize_template('Layout', record) 
     end 
     end 
    end 

    # Initialize an ActionView::Template object based on the record found. 
    def initialize_template(type, record) 
     source = record.body 
     identifier = "#{type} - #{record.id} - #{record.path.inspect}" 
     handler = ActionView::Template.registered_template_handler(record.handler) 

     details = { 
      :format => Mime[record.format], 
      :updated_at => record.updated_at, 
      :virtual_path => virtual_path(record.path, record.partial) 
     } 

     ActionView::Template.new(source, identifier, handler, details) 
    end 

    # Make paths as "users/user" become "users/_user" for partials. 
    def virtual_path(path, partial) 
     return path unless partial 
     if index = path.rindex("/") 
     path.insert(index + 1, "_") 
     else 
     "_#{path}" 
     end 
    end 
end 

當然,這可以被重構相當位,但這是一般的想法。您還需要1或2個數據庫表,這取決於您希望單獨存儲模板和佈局的天氣,或與以下列一起存儲模板和佈局:標題,正文,路徑,格式,區域設置,處理程序,部分

希望有所幫助!