【问题标题】:Call method from ruby file in haml?从haml中的ruby文件调用方法?
【发布时间】:2015-03-15 16:19:00
【问题描述】:

我正在创建一个显示表格的简单 html 页面。在 app.rb 中的 ruby​​ 函数中检索要填充到表中的数据。我正在尝试使用 haml 创建网页。我在为网页创建模板的视图文件夹中有一个 index.haml 文件

%body
 .table-div
   %table
     %tr
       %th //some ruby code to get the table header
     %tr
       %td //create td for each table row.

之后我需要在 app.rb 中调用 ruby​​ 函数 get_table_header() 和 get_table_rows()。这样做的语法是什么?如何在这个 haml 中包含对 ruby​​ 文件的引用?

【问题讨论】:

  • 添加您要执行的功能,以便我改进答案。

标签: ruby haml


【解决方案1】:

要使视图中的控制器可用的方法,您需要在控制器中将其指定为helper 方法。像这样的:

class ApplicationController < ActionController::Base
  helper_method :get_table_header, :get_table_row

  def get_table_header
    < code here >
  end

  def get_table_row
    < code here >
  end
end

查看更多:Helper Methods

然后,有两种方法可以在 HAML 中执行 Ruby 代码。首先,使用“=”符号。这将执行 ruby​​ 代码并写入(显示)返回的结果。我相信这就是您正在寻找的。​​p>

    %body
      .table-div
        %table
          %tr
            %th
              = get_table_header
          %tr
            %td 
              = get_table_row

这与在 ERB 中执行 &lt;%= get_table_row %&gt; 相同。

注意:执行 Ruby 方法不需要括号。其次,这些方法名称看起来像 HTML 部分。您可以将此代码抽象到另一个 HAML 文件中,并使用 Rails Partial 帮助程序调用它们。你可以在这里了解更多Layouts and Rendering in Rails

在 HAML 中执行 Ruby 代码的第二种方法是使用 hiphen。这对条件句很好。例如:

-if <some condition is true>
  = get_table_header
-else
  = get_table_row

这就像在 ERB 中做&lt;% some code %&gt;。返回的结果不会显示在页面上。也适用于映射迭代。如果您有多个表格行,也许可以。

-dog_names = ["Teddy", "Skip", "Humphrey"]
-dogs_names.map do |name|
   %td= name

这将返回 3 个带有名称的标签。

<td>Teddy</td>
<td>Skip</td>
<td>Humphrey</td>

您还可以在控制器中包含如下帮助文件。 这些 Helper 确实会持有 helper 方法。

class YourController < ApplicationController
  include HelperOne
  include HelperTwo
end

【讨论】:

    【解决方案2】:

    使用haml 命令的-r 选项

    haml input.haml output.html -r ./ruby_file.rb
    

    要调用 ruby​​ 函数并将其值插入到输出中,请使用 = 运算符

    %body
     .table-div
       %table
         %tr
           %th= get_table_header 
         %tr
           %td= get_table_rows
    

    【讨论】:

      【解决方案3】:

      您需要将 app.rb 中的函数包含到您的控制器中。

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-16
        • 1970-01-01
        • 2017-03-18
        相关资源
        最近更新 更多