DomTemplate icon indicating copy to clipboard operation
DomTemplate copied to clipboard

Filter bind values

Open g105b opened this issue 4 months ago • 0 comments

This is a nice to have feature.

How many times have you written something like <span data-bind:text="amount">0</span>, just to realise the number comes out as 12345 when really you want it to be 12,345 or even £12,345.00.

So you go to the Entity class and add something like:

#[BindGetter]
function getAmountFormatted():string {
    return number_format($this->amount, 2);
}

and change the HTML to <span data-bind:text="amountFormatted">0</span>.

Wouldn't it be nice to be able to specify a filter to apply to the value, and have somewhere to define all the filters?

Note: the term "filter" is used to stay consistent with PHP's use of the word: https://www.php.net/manual/en/function.stream-filter-register.php - a stream filter works in a similar way to my proposal here.

Proposal:

HTML would look something like this

<span data-bind:text="amount|numericOutput">0</span>

Note the pipe, used similarly to how other types of "pipe" work in programming languages, the amount value will be piped into numbericOutput.

Then there can be a couple of ways to define these filters: on the class itself, a function can be marked as a filter by using the BindFilter attribute:

#[BindFilter]
public function filterNumericOutput(string $input):string {
    return number_format($input, 2);
}

or a filter class can be stored in the root class directory, class/BindFilters.php where all public functions can be used across all bind values on any page/component.

Multiple filters can be piped together:

<span data-bind:text="amount|numericOutput|userCurrency">£0.00</span>

The filterUserCurrency function will need access to the user's currency from somewhere. Let's assume the currency will be set in the database, stored as an enum on the User object that's stored in the Session... there will need to be a sensible way to get a reference to this value from within the filter, preferably using dependency injection rather than having god access to a list of variables. This is the last piece of the puzzle I need to figure out before I can continue with this feature.

g105b avatar Mar 05 '24 15:03 g105b