未找到带有 Liquid 自定义标签的 Rails 3
我正在尝试使用 Rails 3 为一些液体模板创建一组自定义标签。我在 lib/ 目录中添加了一个“liquid_tags.rb”,其内容如下:
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)
当我尝试通过“{%”在我的视图中获取标签时user_controls %}' 它告诉我找不到标签。
有什么想法吗?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没错,正如 marcusmateus 所说,Rails 不会自动加载 lib 目录中的任何内容,即使您已将其添加到 autoload_paths 中,除非文件中的类或模块名称与文件名匹配。
要解决这个问题,只需将自定义格式化程序放入 lib 目录中,每个格式化程序都放在自己的文件中(我尝试使用模块将它们全部包装起来,但没有成功)
然后创建一个初始化程序(在 config/initializers 中)负责注册自定义标记与液体。 IE
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)
Then created an initializer (in config/initializers) responsible for registering the custom tags with Liquid. i.e.
您确定该文件正在加载吗?如果不是,则永远不会调用 register_tag 。我会在 register_tag 上面添加一个 put 语句来调试它,确保文件实际上正在加载。您可以将 register_tag 移动到初始值设定项中
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
在 config/application.rb 上尝试添加这一行
on config/application.rb try adding this line
我相信只有当文件名与其包含的类的名称匹配时才会自动加载文件。在问题中,您声明您的文件名为“liquid_tags.rb”,但您的类名为 UserControls...如果您重命名您的文件“user_controls.rb”,它应该开始自动加载。
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: