简体   繁体   中英

How to access global Sinatra configs inside custom Liquid template tags?

I'm trying to create a custom Liquid template tag like this:

class ScriptLoader < Liquid::Tag       
    def initialize(tag_name, filename, tokens)
      super 
      @file = filename
    end
    def render(context)
      settings.cdn_url << 'script/' << @file
    end    
 end

 Liquid::Template.register_tag('script', ScriptLoader)

The above code is in an external file location at : (project_dir)/tags/scriptloader.rb

This file is being included in the app.rb startup file.

The problem though is that the settings variable is empty, even after adding the configs in the app.rb file using the set method.

The response when calling {% script 'myfile' %} in my templates:

Liquid error: undefined method `cdn_url' for Sinatra::Application:Class

Any ideas or guidance would be greatly appreciated!

Thanks!

Ok, so I've managed to work around the issue.

I created a config object in app.rb that loads the configs from a file, iterates over them and calls the set() method for each. This also stores the config key=>value sets in a class constant hash.

I can access the values like this:

class ScriptLoader < Liquid::Tag       
    def initialize(tag_name, filename, tokens)
      super 
      @file = filename
    end
    def render(context)
      MyObject::CONFIG[:cdn_url] << 'script/' << @file
    end    
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM