module ApplicationHelper def set_title(title = "Default title") content_for :title, title end end在布局中 work.html. erb : <%= content_for?(:title) ? content_for(:title) : 'This is a default title' %>推荐答案 Rails中的帮助器是视图中可用的方法(如果包含它们,则是控制器),它们可以避免视图中的代码重复.Helpers in Rails are methods available in views (and controllers if you include them) that allow you to avoid code repetition in views.我代码中的一个帮助器示例是一种为Facebook登录按钮呈现html的方法.实际上,此按钮比用户看到的要多得多,因为它是带有一些其他信息的隐藏表单,因此,我想以此为基础创建一个辅助方法,因此不必多次复制10行代码,而可以调用a单一方法.这更干了.An example of a helper from my code is a method that renders html for facebook login button. This button is in reality more than user sees, because it's a hidden form with some additional information, etc. For this reason I wanted to make a helper method out of it, so instead of copying 10 lines of code multiple times I can call a single method. This is more DRY.现在,回到您的示例,您想做两件事Now, back to your example, you want to do two things显示页面<title>,在页面顶部添加<h1>标头.display page <title>,add <h1> header at the top of the page.我现在看到链接的答案还不够清楚.您确实需要帮助者,但是您也需要调用它!所以I see now where linked answer wasn't clear enough. You indeed need helper, but you also need to call it! So# application_helper.rbdef set_title(title = "Default title") content_for :title, titleend# some_controller.rbhelper :applicationdef index set_title("Morning Harwood")end然后在布局视图中可以使用:And then in layout's views you can use:<title> <%= content_for?(:title) ? content_for(:title) : 'This is a default title' %><</title>...<h1><%= content_for?(:title) ? content_for(:title) : 'This is a default title' %></h1> 这篇关于在Rails中创建助手时的未定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 14:01