Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Kino.DataTable formatting

kino_data_table_formatting.livemd

Kino.DataTable formatting

Mix.install(
  [
    {:kino, github: "kipcole9/kino", env: :dev},
    :ex_cldr_dates_times,
    :jason
  ],
  config: [
    ex_cldr: [default_backend: MyApp.Cldr]
  ]
)

Define a Cldr Backend Module

This livebook uses a Kino DataTable formatter built into ex_cldr from version 2.39.0. As a result we need a Cldr backend module defined. Note that we also need a default locale defined in the configuration above.

defmodule MyApp.Cldr do
  use Cldr,
    locales: [:en, :de, :fr, :ja],
    default_locale: :en,
    providers: [Cldr.Number, Cldr.DateTime, Cldr.Calendar]
end

Using a configured Kino DataTable formatter

Cldr.Kino.DataTable.value_to_string/2 is the same as the default implementation with two changes:

  1. The formatter uses the Cldr.Chars protocol instead of the String.Chars protocol. This is implemented in ex_cldr libraries for dates, times, numbers, units of measure, locales.
  2. The key :__column__ is passed when the request is to format a column heading. In the Cldr.Kino.DataTable.value_to_string/2 implementation, column headings are converted to strings and capitalized.

Note lastly that there is compiler warning on Elixir 1.17 for ex_cldr_calendars - this is fixed on the main branch and will be release when I finalise implementation of the new calendar callbacks.

# Change the locale between :fr, :ja and :en and the formatting is different.
# We use `Cldr.put_default_locale/1` because `Cldr.put_locale/1` sets
# the locale of the *current* process, and the Kino datatable runs in
# a different process and we have no place to pass the locale into that
# process.
Cldr.put_default_locale(:en)

data = [
  %{
    id: 1,
    name: "Elixir",
    website: "https://elixir-lang.org",
    downloads: 1_000_000.23,
    first_released: ~D[2010-05-26]
  },
  %{
    id: 2,
    name: "Erlang",
    website: "https://www.erlang.org",
    downloads: 2_000_000.45,
    first_released: ~D[1980-03-11]
  }
]

Kino.DataTable.new(data, formatter: &Cldr.Kino.DataTable.format/2)