Laravel Blade指令用于2或4位数字。

huangapple go评论60阅读模式
英文:

Laravel Blade Directive for number with 2 or 4 digits

问题

I am trying to make a "dynamic" custom blade directive which fails because it receives the variable name and not the float. (latest laravel version)

我正在尝试创建一个“动态”的自定义刀片指令,但失败了,因为它接收到变量名而不是浮点数。(最新版本的Laravel)

I wanted to extend that one:

Blade::directive('money', function ($money) {
    return "<?php echo number_format($money, 2, ',', ''); ?>";
});

我想扩展上面的代码:

with an if statement if (str_ends_with($money, "00")) ... which will of cause not work, what I found out.

使用一个if语句 if (str_ends_with($money, "00")) ... 是不起作用的,这是我发现的。

Is there any other way to fulfill this task?

有没有其他方法来完成这个任务?

12.3400 should be displayed as 12,34

12.3400应该显示为12,34

12.3401 should be displayed as 12,3401

12.3401应该显示为12,3401

if there is no other solution:
for the moment i am using a blade component

如果没有其他解决方案:
目前我正在使用一个刀片组件

@props(['money'])

@if (str_ends_with($money, '00'))
{{ number_format($money, 2, ',', '') }}
@else
{{ number_format($money, 4, ',', '') }}
@endif

英文:

I am trying to make a "dynamic" custom blade directive which fails because it receives the variable name and not the float. (latest laravel version)

I wanted to extend that one:

Blade::directive(&#39;money&#39;, function ($money) {
    return &quot;&lt;?php echo number_format($money, 2, &#39;,&#39;, &#39;&#39;); ?&gt;&quot;;
});

with an if statement if (str_ends_with($money, &quot;00&quot;)) ... which will of cause not work, what I found out.
Is there any other way to fullfill this task?

12.3400 should be displayed as 12,34

12.3401 should be displayed as 12,3401

if there is no other solution:
for the moment i am using a blade component

@props([&#39;money&#39;])

@if (str_ends_with($money, &#39;00&#39;))
    {{ number_format($money, 2, &#39;,&#39;, &#39;&#39;) }}
@else
    {{ number_format($money, 4, &#39;,&#39;, &#39;&#39;) }}
@endif

答案1

得分: 0

尝试将'$money'传递给str_ends_with()方法:

Blade::directive('money', function ($money) {
    return "<?php echo str_ends_with('$money', '00') ? number_format($money, 2, ',', '') : number_format($money, 4, ',', ''); ?>";
});
英文:

Try passing '$money' in str_ends_with() method:

  Blade::directive(&#39;money&#39;, function ($money) {
     return &quot;&lt;?php echo str_ends_with(&#39;$money&#39;, &#39;00&#39;) ? number_format($money, 2, &#39;,&#39;, &#39;&#39;) : number_format($money, 4, &#39;,&#39;, &#39;&#39;); ?&gt;&quot;;
  });

huangapple
  • 本文由 发表于 2023年4月17日 19:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定