Laravel Blade - 自定义助手 [英] Laravel Blade - custom helper
问题描述
我有很多数字的表格,我想对所有数字都使用数字格式.所以现在我有这个:
I have table with a lot of numbers and I want to use number format for all of them. So right now I have this:
<tbody>
@foreach($table['float']['chips_amount'] as $float)
<tr>
<td class="no-border"></td>
<td class="text-right chip-width">{{ number_format($float['chips']['value'], 0, ' ', ' ') }}</td>
<td class="text-right count-width">{{ $float['count'] }}</td>
<td class="text-right">{{ number_format($float['chips']['value'] * $float['count'], 0, ' ', ' ') }}</td>
</tr>
@endforeach
<tr>
<td class="no-border" colspan="3"></td>
<td class="text-right value-width bold-border">{{ number_format($table['float']['amount'], 0, ' ', ' ') }}</td>
</tr>
</tbody>
但我只是在重复相同的函数 number_format() 并且当有人决定格式会不同时可能会出现问题.然后我必须更改表格中的所有格式.我对 Nette 框架有一些经验,并且存在我可以拥有自定义助手然后在模板中使用它的选项,即: {{ $anyNumber|myCustomFormat }}
在管道之后我有自己的自定义助手.Laravel Blade 模板中有类似的东西吗?我在文档中没有找到任何关于此的内容.
But I'm just repeating the same function number_format() and there could be problem when somebody decide that format will be different. Then I have to change all formats in table. I have some experience with Nette framework and there exists option that I can have custom helper and then use it in template, i.e: {{ $anyNumber|myCustomFormat }}
where after pipeline I have my own custom helper. Is there something like that in Laravel Blade templates? I didn't find anything about this in documentation.
推荐答案
您可以创建自己的刀片帮助文件.
创建您的文件(例如在 app/Helpers/bladeHelpers.php 中)并添加代码.例如;
You can create your own blade help file.
Create you file (say in app/Helpers/bladeHelpers.php) and add code. For example;
<?php
if (! function_exists('my_custom_number_formt')) {
/**
* Format number
*
* @param $value
* @param $attribute
* @param $data
* @return boolean
*/
function my_custom_number_formt($value)
{
return number_format($value, 0, ' ', ' ');
}
}
然后将此文件添加到您的 composer.json 中的 autoload 部分(记得在 psr4 声明中根据您的项目设置命名空间);
Then add this file to your composer.json in the autoload section (remember to set the namespace as per your project in the psr4 declaration);
{
... rest of file
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\": "app/",
"MyApp\Custom\": "src/"
},
"files": [
"app/Helpers/bladeHelpers.php"
]
},
... rest of file
}
注意,此时您可能需要清除缓存.
N.B You may want to clear your cache at this point.
然后在你的刀片文件中使用;
Then use in your blade files;
<td class="text-right chip-width">{{ my_custom_number_formt($float['chips']['value']) }}</td>
这篇关于Laravel Blade - 自定义助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!