咨询:能否将Tabulator.info的多个格式化器组合为一个?
Absolutely! Tabulator fully supports combining multiple formatters within a custom formatter function—this is a super useful pattern for cases where you need to apply multiple styling/formatting rules to a cell's content.
The key thing to note is that you don't want to concatenate the outputs of separate formatters (like your initial example suggests), because that would duplicate the cell value. Instead, you should nest the formatters: pass the result of one formatter as the input to another.
Example 1: Directly Using Built-in Formatters
Tabulator exposes all its built-in formatters under Tabulator.formatters, so you can call them directly in your custom function. Here's how to combine the bold and euro formatters properly:
formatter: function(cell) { // First format the value as Euro, then wrap it in bold const euroFormattedValue = Tabulator.formatters.euro(cell); // Create a mock cell object that returns the Euro-formatted value // This lets the bold formatter process the already formatted text const mockCell = { getValue: () => euroFormattedValue }; return Tabulator.formatters.bold(mockCell); }
Example 2: Using a Custom getFormatter Helper
If you want to reuse this pattern across multiple columns, you can wrap the formatter calls in a helper function like you mentioned:
// Helper function to fetch and apply a formatter function getFormatter(formatterName, cellOrValue) { const formatter = Tabulator.formatters[formatterName]; if (!formatter) return typeof cellOrValue === 'object' ? cellOrValue.getValue() : cellOrValue; // If we're passing a raw value, create a mock cell for the formatter if (typeof cellOrValue !== 'object') { return formatter({ getValue: () => cellOrValue }); } return formatter(cellOrValue); } // Use it in your column definition formatter: function(cell) { // Chain the formatters: Euro first, then bold return getFormatter('bold', getFormatter('euro', cell)); }
Important Notes
- Order matters: In the examples above, we first apply the Euro formatting (which adds the currency symbol) then wrap it in bold. Reverse the order if you want to bold the value first, then add the symbol.
- Avoid concatenation: Doing
getFormatter('bold', cell) + getFormatter('euro', cell)would show something like<strong>100</strong>€100—not what you want! Nesting ensures the formatting is applied to the same value once. - Custom formatters work too: This pattern also works with your own custom formatters, not just built-in ones. Just make sure your formatter functions accept a cell-like object with a
getValue()method.
内容的提问来源于stack exchange,提问作者Bernhard

