demo D209
A unit family of your own in htmx
Register a unit system from symbols and their factors
registerUnitSystem · createUnitType
This grid registers a unit family of your own from its symbols and their conversion factors, then uses it like any built-in unit type. It lets a column speak a domain's own units, parsed and converted correctly, without waiting for the unit to be built in.
This is the htmx version. A server-rendered table is upgraded in place, so the page is readable before any script runs and gains the full grid when the module loads, which suits a progressively enhanced app.
The configuration
<link rel="stylesheet" href="https://cdn.latticegrid.dev/lattice-grid@1.107.0/lattice-grid.min.css">
<!-- A real, server-rendered table: readable with JavaScript off. data-field on
each header names the column that cell becomes, and data-id on each row is
the key the grid carries it under. -->
<table id="custom-units-table" data-lattice-grid>
<thead>
<tr>
<th data-field="yarn">Yarn</th>
<th data-field="count">Linear density</th>
</tr>
</thead>
<tbody>
<tr data-id="1"><td>Y-001</td><td>1084.13</td></tr>
<tr data-id="2"><td>Y-002</td><td>2169.15</td></tr>
<tr data-id="3"><td>Y-003</td><td>3198.25</td></tr>
<!-- the rest of the rows, rendered by your server -->
</tbody>
</table>
<script type="module">
import { hydrateTable, registerUnitSystem, defineUnit, createUnitType } from 'https://cdn.latticegrid.dev/lattice-grid@1.107.0/modules/htmx.esm.min.js';
// A unit family of your own. factor is how many base units one of these is;
// exactly one must be 1. The factors are the ladder, sorted at load.
registerUnitSystem('yarn', [
defineUnit('tex', 1, ['tx']),
defineUnit('ktex', 1e3, [], { prefix: 'k' }),
defineUnit('den', 1 / 9, ['denier']),
]);
// The markup carries the rows; a server-rendered table's column types are
// declared in the config hydrateTable takes. The grid replaces the table
// where it stood.
const grid = hydrateTable(document.getElementById('custom-units-table'), {
dataTypes: {
linearDensity: createUnitType({ system: 'yarn', unit: 'tex', display: 'auto' }),
},
columns: [
{ field: 'yarn', title: 'Yarn', layout: { pin: 'start', width: 130 } },
{ field: 'count', title: 'Linear density', type: 'linearDensity', total: 'median' },
],
});
</script>