要使视图中的控制器可用的方法,您需要在控制器中将其指定为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 中执行 <%= get_table_row %> 相同。
注意:执行 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 中做<% some code %>。返回的结果不会显示在页面上。也适用于映射迭代。如果您有多个表格行,也许可以。
-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