如何通过任意 erb 文件访问任意视图助手的方法?

发布于 2024-11-19 08:58:20 字数 81 浏览 3 评论 0原文

按照惯例,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光飞翔i 2024-11-26 08:58:20

如果您需要这样做,则说明您的代码组织有问题。相反,将两个视图所需的辅助方法移至一个公共模块中,并将该模块包含在两个视图中。

例如,如果您有:

module ApplesHelper
  def flavor_of(fruit)
  end
end

并且您希望 /bananas 视图能够访问 flavor_of 方法,则执行以下操作:

module Flavored
  def flavor_of(fruit)
    # ...
  end
end

module ApplesHelper
  include Flavored
end

module BananasHelper
  include Flavored
end

更新: 我意识到我实际上并没有回答直接问原问题。在视图中包含另一个助手的方法是使用 helper

class BananasController ...
  helper ApplesHelper
end

现在所有 /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:

module ApplesHelper
  def flavor_of(fruit)
  end
end

and you want /bananas views to have access to the flavor_of method, then do this:

module Flavored
  def flavor_of(fruit)
    # ...
  end
end

module ApplesHelper
  include Flavored
end

module BananasHelper
  include Flavored
end

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:

class BananasController ...
  helper ApplesHelper
end

Now all /bananas view also have the ApplesHelper methods available to them.

提笔落墨 2024-11-26 08:58:20

如果我很好地理解这个问题,你必须定义你的方法助手:

module ControllerHelper
   def function_you_have_to_call
      some_code_here
   end
end

当你想通过 *.erb 文件调用你的方法助手时,你必须在视图中插入它:

<% function_you_have_to_call %>

如果你的方法有一个返回值并且你想要要将其存储在视图中定义的局部变量中,请尝试:

<% value_you_want = function_you_have_to_call %>

记住 <% %> 包含的代码仅由 ruby​​ 解释,不会由视图显示。在这种情况下,您必须使用 <%= %> 包含的代码。

现在您可以访问 value_you_want 并可能使用 for 语句。

If I understood well the question, you have to define your method helper with:

module ControllerHelper
   def function_you_have_to_call
      some_code_here
   end
end

When you want to call your method helper by the *.erb file, you have to insert this in the view:

<% function_you_have_to_call %>

If your method has a return value and you want to store it in an local variable defined in your view, try:

<% value_you_want = function_you_have_to_call %>

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文