class TableComponent
TableComponent
represents an HTML table generated from an Enumerable
collection.
Attributes in an TableComponent
are separated into multiple groups since there are multiple kinds of tags. These groups are:
-
table - The attributes associated with the <table> element.
-
header - The attributes associated with <tr> element representing the header.
-
header_cell - The attributes associated with <th> elements.
-
row - The attributes associated with all <tr> elements, including the header.
-
cell - The attributes associated with <td> and <th> elements.
Refer to other components for the format for applying attributes.
Public Class Methods
Creates a new instance of TableComponent
from the values of rows.
rows is an Enumerable
collection of Enumerable
objects.
If a block is given, each item in rows is passed to it to render the table cells, not including the header. If no block is given, rows is used directly.
# File lib/html-native/collections.rb, line 261 def initialize(rows, col_names: [], row_names: [], attributes: {}, &block) @rows = rows.map(&:to_a) @header = col_names.to_a row_names = row_names.to_a unless row_names.empty? row_names.each_with_index do |name, i| if i < @rows.size @rows[i].prepend(name) else @rows << [name] end end end @header.prepend("") unless row_names.empty? || @header.empty? @table_attributes = attributes[:table] || {} @header_attributes = attributes[:header] || {} @header_cell_attributes = attributes[:header_cell] || {} @row_attributes = attributes[:row] || {} @cell_attributes = attributes[:cell] || {} @block = block end
Public Instance Methods
Converts the TableComponent
instance to the equivalent HTML.
render can be called directly, but that usually isn't necessary. HTMLComponent::Builder
handles this automatically, so it only needs to be done if there is no prior instance of one.
# File lib/html-native/collections.rb, line 289 def render table(@table_attributes) do unless @header.empty? tr(@row_attributes.merge(@header_attributes)) do @header.component_map do |h| th(@cell_attributes.merge(@header_cell_attributes)) {h} end end else Builder.new end + @rows.component_map do |row| attributes = {row: @row_attributes, cell: @cell_attributes} TableRowComponent.new(row, attributes: attributes, &@block) end end end