2014-04-09 45 views
1

我试图访问我有我的应用程序控制器文件中这样定义的辅助方法current_tenant:无法获得液体标签定义中current_tenant helper方法

def current_tenant 
    @current_tenant ||= User.find_by_alias_domain(request.host) 
    @current_tenant ||= User.find_by_subdomain!(request.subdomain) # includes(:home). 
end 
helper_method :current_tenant 

我婉从里面这个访问类。但是我无法让它工作。

class GetMenu < Liquid::Tag 

     def initialize(tag_name, variables, tokens) 

      @variables = variables.split(" ") 

      @menu_object = @variables[0] 
      @file_name = @variables[1] 

      super 
     end 

     def render(context) 
      #@path = Liquid::Template.file_system 
      #header_file = @path.root.to_s + "/partials/#{@file_name.strip}.html.liquid" 

      #content = File.read(header_file) 


      content = current_tenant.theme.code_file.find_by_hierarchy_and_name('snippet', @file_name.to_s).code 

      @menu ||= Menu.find_by_slug(@menu_object) 

      context.merge('menu' => @menu) 

      Liquid::Template.parse(content).render(context) 

     end 

    end 

    Liquid::Template.register_tag('get_menu', GetMenu) 

end 

任何帮助表示赞赏:)

+0

对不起,我的无知,但液体::标签从ApplicationController中任何方式继承? –

+0

@StavrosSouvatzis我不这么认为。 AFAIK的想法是,它不会得到控制器的参考。它应该与轨道世界分开。 – phoet

+0

那么你认为它会知道你的方法的存在?您需要将其用于您使用它的类的领域。要么需要ApplicationController(yaiks),要么将您的方法放在助手文件中(例如application_helper.rb),并且要求在ApplicationController和GetMenu类中 –

回答

0

我通过将当前租户的液体变量在我的盘活方法,像这样解决了这个:

Liquid::Template.parse(layout_code).render(model_content.merge('template_content' => templ, 'settings' => current_tenant, 'theme_id' => current_tenant.theme.id), :filters => [LiquidFilters]) 

最重要的部分是:

'settings' => current_tenant, 'theme_id' => current_tenant.theme.id 

这两个增加了一个名为settings和theme_id的液体变量,其中包含主题id和current_tenant。

这些变量可以在模板文件(液体文件)中正常访问,也可以在液体标签定义中通过context["theme_id"]访问。

完整的示例:

class SnippetFile < Liquid::Tag 
    class SnippetFile < Liquid::Tag 
     # Include the stylesheet tag link helper 
     include ActionView::Helpers::AssetTagHelper 

     def initialize(tag_name, variables, tokens) 
      @variables = variables.split(" ") 


      @default_name = @variables[0] 
      @file_name = @variables[1] 

      super 
     end 

     def render(context) 

      if @file_name.present? && (context[@file_name.strip]).present? 
       content = CodeFile.find_by(hierarchy: 'snippet', name: context[@file_name.strip], theme_id: context["theme_id"]) 
      else 
       content = CodeFile.find_by(hierarchy: 'snippet', name: @default_name, theme_id: context["theme_id"]) 
      end 

      Liquid::Template.parse(content.code).render(context) 

     end 


    end 

    Liquid::Template.register_tag('snippet_file', SnippetFile)