Вопрос

I am trying to access the helper method current_tenant that I have defined inside my applications controller file like this:

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

I wan to access it from inside this class. However I can't get it to work.

    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

Any help is appreciated :)

Это было полезно?

Решение

I solved this by adding the current tenant to the liquid variables in my liquidize method like so:

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

The important part is:

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

These two adds a liquid variable named settings and theme_id which contains the theme id and the current_tenant.

These varaibles can be accessed normally within the template files (liquid files) or through context["theme_id"] when inside a liquid tag definition.

Full example:

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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top