【问题标题】:How do I call a Rails helper method from inside another helper method?如何从另一个辅助方法内部调用 Rails 辅助方法?
【发布时间】:2011-03-27 02:40:08
【问题描述】:

我正在编写一个助手,它需要调用另一个助手来生成 html。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby helpers


    【解决方案1】:

    试试:
    包括另一个助手

    【讨论】:

      【解决方案2】:

      随便叫吧。

      如果它位于不同的帮助文件中,您的控制器可以使用控制器方法“helper”包含其他帮助文件

      添加:

      这是一个例子:

      # in the view
      <%= my_helper %>
      
      # in the helper file
      def my_helper
        "<div>" + someother_helper_which_generates_html + "</div>"
      end
      

      ** 如果这没有帮助,请在您的问题中添加更多详细信息......

      【讨论】:

      • 这个答案没有解决这个问题。它询问如何在另一个 Helper 中使用一个 Helper,而不是在 View 中演示 Helper 的用法.
      【解决方案3】:

      这样的东西应该可以帮助你(比如,在 application_helper.rb 中)

      module ApplicationHelper
      
        def create_div
          html("this is some content")
        end
      
        def html(content)
          "<div>#{content}</div>"
        end
      
      end
      

      在这种情况下,create_div 方法以字符串作为参数调用 html 方法。 html 方法返回一个 HTML 字符串,其中包含您提供的嵌入参数。在视图中,它看起来像:

      <%= create_div %>
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2014-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-12-30
        • 2016-07-22
        • 1970-01-01
        • 2019-06-05
        • 2011-10-26
        • 2011-08-22
        相关资源
        最近更新 更多