1
votes

I am using Laravel 7. I am thinking of using Blade directive to format numbers in my view. But I'm having problem with the variable showing up in the final output.

Here is a simplified version of my original code that works. (The actual code has a number of conditional @if to format the number differently depending on the value.)

<div>{{ number_format( $stat->number1,0,'.',',' ) }}</div>
<div>{{ number_format( $stat->number2,0,'.',',' ) }}</div>
<div>{{ number_format( $stat->number3,0,'.',',' ) }}</div>

Here is the custom directive I created.

Blade::directive('format_number_thousand_sep', function ($expression) {
    return "{{ number_format( $expression,0,'.',',' ) }}";
});

Here is the blade template that I've changed to call this directive. When I run this, it gives me an error "number_format() expects parameter 1 to be float, string given". I figured the string "$stat->number1" is being used instead of the value of the variable.

<div>@format_number_thousand_sep( '$stat->number1' )</div>
<div>@format_number_thousand_sep( '$stat->number2' )</div>
<div>@format_number_thousand_sep( '$stat->number3' )</div>

To troubleshoot, I modified the directive to just return the variable to make sure it displays on the output. I've tried variations like the ones below and the output is an error (e.g. unexpected '{'), the literal string "$stat->number1", or a partial string because the "

return "$expression";

return "{{ $expression }}";

return "<?php echo '{{' . $expression . '}}'; ?>";

I've tried researching this online. Most questions seems to be trying to use the value of the variable within the directive, which I know wouldn't work. I just want the output to include the proper syntax so the variable value will be inserted in the output.

What is the proper syntax for passing a variable name to a blade directive and have it evaluate properly in the final output?

1

1 Answers

0
votes

I'm not sure but can you try like this:

Blade::directive('format_number_thousand_sep', function ($expression) {
    return number_format( $expression,0,'.',',' );
});