rails 3.1通过模板解析器模板特定的布局?

问题描述:

我有一个非常简单的模板解析器从数据库返回的模板: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”',将被忽略。所有渲染的都是视图的内容 - 根本没有布局。 –

你不得不做这样的事情:

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个数据库表,这取决于您希望单独存储模板和布局的天气,或与以下列一起存储模板和布局:标题,正文,路径,格式,区域设置,处理程序,部分

希望有所帮助!