Class: CCS::Components::GovUK::Table

Inherits:
Base
  • Object
show all
Defined in:
lib/ccs/components/govuk/table.rb,
lib/ccs/components/govuk/table/body/data_cell.rb,
lib/ccs/components/govuk/table/body/head_cell.rb,
lib/ccs/components/govuk/table/header/head_cell.rb

Overview

GOV.UK Table

This is used to generate the table component from the GDS - Components - Table

Defined Under Namespace

Classes: Body, Header

Constant Summary collapse

DEFAULT_ATTRIBUTES =

The default attributes for the table

{ class: 'govuk-table' }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(rows:, head_cells: nil, caption: nil, first_cell_is_header: nil, **options) ⇒ Table

Returns a new instance of Table.

Parameters:

  • rows (Array<Array<Hash>>)

    array of table rows and cells. See Body::HeadCell#initialize or Body::DataCell#initialize for details of the items in the array.

  • head_cells (NilClass, Array) (defaults to: nil)

    array of table head cells. See Header::HeadCell#initialize for details of the items in the array.

  • caption (NilClass, Hash) (defaults to: nil)

    options for a table caption

  • first_cell_is_header (Boolean) (defaults to: nil)

    if set to true, first cell in table row will be a TH instead of a TD

  • options (Hash)

    options that will be used in customising the HTML

Options Hash (caption:):

  • :text (String)

    the caption text

  • :classes (String)

    additional CSS classes for the table caption

Options Hash (**options):

  • :classes (String)

    additional CSS classes for the table HTML

  • :attributes (Hash) — default: {}

    any additional attributes that will be added as part of the HTML



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ccs/components/govuk/table.rb', line 43

def initialize(rows:, head_cells: nil, caption: nil, first_cell_is_header: nil, **options)
  super(**options)

  @rows = rows.map do |row_cells|
    row_cells.map.with_index do |row_cell, index|
      if first_cell_is_header && index.zero?
        Body::HeadCell.new(context: @context, **row_cell)
      else
        Body::DataCell.new(context: @context, **row_cell)
      end
    end
  end
  @head_cells = head_cells&.map { |head_cell| Header::HeadCell.new(context: @context, **head_cell) }
  @caption = caption
end

Instance Method Details

#renderActiveSupport::SafeBuffer

Generates the HTML for the GOV.UK table component

Returns:

  • (ActiveSupport::SafeBuffer)


63
64
65
66
67
68
69
70
71
# File 'lib/ccs/components/govuk/table.rb', line 63

def render
  tag.table(**options[:attributes]) do
    concat(table_caption) if caption
    concat(table_head) if head_cells
    concat(tag.tbody(class: 'govuk-table__body') do
      rows.each { |row_cells| concat(table_row(row_cells)) }
    end)
  end
end