代码之家  ›  专栏  ›  技术社区  ›  Jaroslav Klimčík

Laravel刀片-自定义辅助工具

  •  0
  • Jaroslav Klimčík  · 技术社区  · 8 年前

    我有一张有很多数字的表格,我想对所有数字都使用数字格式。所以现在我有这个:

    <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 framework有一些经验,并且有一个选项,我可以使用自定义助手,然后在模板中使用它,即: {{ $anyNumber|myCustomFormat }} 我有自己的自定义助手。Laravel刀片模板中有类似的东西吗?我在文档中找不到任何与此相关的内容。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Rooneyl    8 年前

    您可以创建自己的刀片帮助文件。
    创建你的文件(比如 应用程序/助手/bladeHelpers。php )并添加代码。例如

    <?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, ' ', ' ');
    
        }
    
    }
    

    然后将此文件添加到 创作者json 在 自动加载 节(记住根据psr4声明中的项目设置名称空间);

    {
    ... rest of file
    "autoload": {
            "classmap": [
                "database"
            ],
            "psr-4": {
                "App\\": "app/",
                "MyApp\\Custom\\": "src/"
            },
            "files": [
                "app/Helpers/bladeHelpers.php"
            ]
        },
    ... rest of file
    }
    

    注意:此时您可能需要清除缓存。

    然后在你的刀片文件中使用;

    <td class="text-right chip-width">{{ my_custom_number_formt($float['chips']['value']) }}</td>