php - 当字符串与变量连接时创建自定义 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 指令将不起作用,因为外部引号也是单引号。但无论如何,我觉得创建这个字符串太难了,我想知道,有没有更简单的方法来生成最终的字符串来回显结果?
解决方案
根据您的信息,这是我得到的:
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 . '?>');
});
推荐阅读
- java - 将 ImageIcon 添加到 JLabel
- javascript - 组内的导入源必须按字母顺序排列 (TS)
- javascript - Google Treemap:想要将节点的颜色设置为红色、绿色和琥珀色
- r - 从 Map 中的列表中获取对象的名称
- specman - Specman e:“keep type .. is a”无法细化字段的类型
- c# - 为什么 EF 核心中的 [Timestamp] 列由 byte[] 列而不是 UInt64 支持
- client - 使用 Hazelcast Executor Service 在客户端上执行
- ubuntu - 如何在 ubuntu 16.04 上安装 Tensorflow GPU
- c# - 创建扩展名为“log”的日志文件
- django - HTML