helper 和 helper_method 的作用是什么?
helper_method
很简单:它使控制器的部分或全部方法可供视图使用。
什么是助手
?是否相反,即将辅助方法导入到文件或模块中? (也许名称 helper
和 helper_method
很相似。它们可能是 share_methods_with_view
和 import_methods_from_view
)
helper_method
is straightforward: it makes some or all of the controller's methods available to the view.
What is helper
? Is it the other way around, i.e., it imports helper methods into a file or a module? (Maybe the name helper
and helper_method
are alike. They may rather instead be share_methods_with_view
and import_methods_from_view
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
helper_method
方法是显式共享控制器中定义的一些方法,使它们可供视图使用。这用于您需要从控制器和帮助器/视图访问的任何方法(标准帮助器方法在控制器中不可用)。例如,常见用例:另一方面,
helper
方法用于将整个助手导入到控制器(及其继承的控制器)提供的视图中。这意味着For Rails > 3.1
使所有辅助模块可用于所有视图(至少对于从 application_controller 继承的所有控制器)。
使 UserHelper 方法可用于视图以执行主控制器的操作。这相当于执行以下操作:
The method
helper_method
is to explicitly share some methods defined in the controller to make them available for the view. This is used for any method that you need to access from both controllers and helpers/views (standard helper methods are not available in controllers). e.g. common use case:the
helper
method on the other hand, is for importing an entire helper to the views provided by the controller (and it's inherited controllers). What this means is doingFor Rails > 3.1
makes all helper modules available to all views (at least for all controllers inheriting from application_controller.
makes the UserHelper methods available to views for actions of the home controller. This is equivalent to doing:
下面是一个简化上述定义的示例:
这是一段代码,您将在视图中看到类似这样的内容:
我们可以稍微清理一下并将其放入助手中:
然后在视图代码中,您调用helper 方法并将其作为参数传递给用户。
这种提取使视图代码更易于阅读,特别是如果您明智地选择辅助方法名称。
所以我希望这能让你明白一些事情。
报价来源
代码源
Here's an example to simplify the above definition:
Here is a code, where you would have something like this in the view:
We can clean it up a little bit and put it into a helper:
And then in the view code, you call the helper method and pass it to the user as an argument.
This extraction makes the view code easier to read especially if you choose your helper method names wisely.
So I hope this clears things up a little for you.
Source for the quotation
Source for the code