首页 > 解决方案 > 当字符串与变量连接时创建自定义 Laravel Blade 指令的更简单方法

问题描述

我创建了以下刀片指令:

    Blade::directive('bundle', function ($component) {
        $string = "\":langs='\" . file_get_contents(base_path() . \"/resources/bundles/\" . App::currentLocale() . \"/$component.json\").\"'\";";
        return ("<?php echo " . $string . "?>");
    });

为了更好地理解发生了什么,这是我想用上面的字符串表示的代码(但作为 Blade 指令,这不是一个选项):

$path = base_path() . "\\resources\\bundles\\" . App::currentLocale() ."\\$component.json";
$json = file_get_contents($path);
return "<?php echo \":langs='\" $json \"'\"; ?>

就像现在一样,当 .json 文件中有单引号时,上面的 Blade 指令将不起作用,因为外部引号也是单引号。但无论如何,我觉得创建这个字符串太难了,我想知道,有没有更简单的方法来生成最终的字符串来回显结果?

标签: phplaravellaravel-bladedirective

解决方案


根据您的信息,这是我得到的:

Blade::directive('bundle', function ($component) {
    $encoding = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
    $component = trim($component, "'\" ");

    $string = sprintf(
        '":langs=\'" . json_encode(json_decode(file_get_contents(%s), true), %d) . "\'"',
        'resource_path("bundles/" . App::getLocale() . "/' . $component . '.json")',
        $encoding
    );

    return ('<?php echo ' . $string . '?>');
});

推荐阅读