如何将 i18n 翻译方法与 Draper gem 一起使用?
我使用 Draper gem 来装饰我的模型。这里我有非常经典的设置:
# app/decorators/subject_decorator.rb
class SubjectDecorator < ApplicationDecorator
decorates :subject
def edit_link
h.link_to(h.t('.edit'), '#')
end
end
我使用 i18n 进行国际化。但是当我运行这个时,我得到:
Cannot use t(".edit") shortcut because path is not available
所以我想知道以前是否有人这样做过?它应该非常简单。
I use Draper gem to decorate my models. Here I have pretty classic settings:
# app/decorators/subject_decorator.rb
class SubjectDecorator < ApplicationDecorator
decorates :subject
def edit_link
h.link_to(h.t('.edit'), '#')
end
end
I use i18n for internationalization. But when I run this, I get:
Cannot use t(".edit") shortcut because path is not available
So I was wondering if anyone has done this before? It should be pretty straight forward.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是你不能在装饰器中利用延迟查找,因为它们不没有任何上下文来确定视图文件级别(索引、显示、编辑等)。因此,开箱即用,您只需拼出整个内容,例如
t('subjects.show.edit')
或其他内容。这就是我最终所做的事情,让它对我有所帮助。
这不会为您提供完整的
subjects.show.edit
参考,您只会获得subjects.edit
但对我来说似乎总比没有好。The problem is you can't take advantage of lazy lookup in decorators because they don't have any context to determine the view file level (index, show, edit, etc.). So out of the box you just need to spell out the whole thing like
t('subjects.show.edit')
or whatever.Here's what I wound up doing to get it somewhat working for me.
This won't get you the full
subjects.show.edit
reference, you'll just getsubjects.edit
but it seemed better than nothing to me.在你的代码中你必须使用:
尝试一下......它应该可以工作
Inside your code you have to use :
give it a try... it should work
您所要做的就是将其添加到装饰器类的顶部...
...它可以处理许多最常见的帮助器方法,包括 i18n 内容。你也可以在 draper 类中放弃写所有这些“h”。
All you have to do is add this to the top of your decorator class...
...and it handles many of the most common helper methods including i18n stuff. You can also ditch writing all those "h's" in your draper class.