如何通过任意 erb 文件访问任意视图助手的方法?
按照惯例,Rails 只“附加”与调用 erb 文件的控制器相对应的视图助手。
如何访问 Rails 中任意视图助手的视图助手方法?
By convention, Rails only "attaches" the view helper which corresponds to the controller the erb file is called of.
How can I access a view helper's methods of an arbitrary view helper in Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要这样做,则说明您的代码组织有问题。相反,将两个视图所需的辅助方法移至一个公共模块中,并将该模块包含在两个视图中。
例如,如果您有:
并且您希望 /bananas 视图能够访问
flavor_of
方法,则执行以下操作:更新: 我意识到我实际上并没有回答直接问原问题。在视图中包含另一个助手的方法是使用
helper
:现在所有 /bananas 视图也都可以使用 ApplesHelper 方法。
If you need to do that, something is wrong with the organization of your code. Instead, move the helper methods that both of your views need into a common module, and include that module in both.
For example, if you have:
and you want /bananas views to have access to the
flavor_of
method, then do this:Update: I realized that I didn't actually answer the original question directly. The way to include another helper in a view is with
helper
:Now all /bananas view also have the ApplesHelper methods available to them.
如果我很好地理解这个问题,你必须定义你的方法助手:
当你想通过 *.erb 文件调用你的方法助手时,你必须在视图中插入它:
如果你的方法有一个返回值并且你想要要将其存储在视图中定义的局部变量中,请尝试:
记住
<% %>
包含的代码仅由 ruby 解释,不会由视图显示。在这种情况下,您必须使用<%= %>
包含的代码。现在您可以访问
value_you_want
并可能使用 for 语句。If I understood well the question, you have to define your method helper with:
When you want to call your method helper by the *.erb file, you have to insert this in the view:
If your method has a return value and you want to store it in an local variable defined in your view, try:
Remember the code included by
<% %>
is only interpreted by ruby and not shown by view. In this case you have to use code included by<%= %>
.Now you can access
value_you_want
and maybe use for statements.