I am trying to create a set of custom tags for some liquid templates using Rails 3. I added a 'liquid_tags.rb' in my lib/ directory with content like this:
class UserControls < Liquid::Tag
def initialize(tag_name)
super
end
def render(context)
tag = "<b>TAG</b>"
end
end
Liquid::Template开发者_开发百科.register_tag('user_controls', UserControls)
When I try to get the tag in my view via '{% user_controls %}' it tells me the tag isn't found.
Any ideas?
Thanks in advance.
That's right, as marcusmateus says, Rails won't load anything in the lib directory automatically even if you have added it to the autoload_paths unless the class or module name inside the file matches the file name.
To sort this problem just put the custom formatters inside the lib directory, each in their own file (I tried using a module to wrap them all up but no luck)
class MyCustomTag < Liquid::Tag
def initialize(tag_name, params, tokens)
# do something
end
def render(context)
# do something
end
end
Then created an initializer (in config/initializers) responsible for registering the custom tags with Liquid. i.e.
Liquid::Template.register_tag('custom_tag', MyCustomTag)
Liquid::Template.register_tag('custom_tag', MyCustomTag2EtcEtc)
Are you sure that file is getting loaded? If it's not, then register_tag is never getting called. I would throw in a puts statement above register_tag to debug it, make sure that the file is actually being loaded. You may to move the register_tag into an initializer
on config/application.rb try adding this line
config.autoload_paths << File.join(config.root, "lib")
I believe files are only autoloaded if the name of the file matches the name of the class it contains. In the question you state that your file is named 'liquid_tags.rb', but your class is named UserControls... if you rename your filed 'user_controls.rb' it should begin autoloading.
I think it's not loading problem -- I have it also. The tag is being loaded, you can print the current registered tags:
Liquid::Template.tags.inspect
精彩评论