Laravel:如何在Blade中翻译含日期的MySQL CONCAT拼接字符串
Laravel 带变量文本的部分翻译实现方案
问题背景
在Laravel中使用__()助手函数可以实现基础翻译,比如Blade模板中:
{{ __("Hello") }}
但遇到固定文本与数据库变量拼接的场景时,直接翻译拼接后的字符串无法生效:
- 控制器通过SQL拼接字符串:
SELECT CONCAT("Commences ", commencement_date) AS calculated_current_year ...
- Blade模板中直接翻译该字段:
{{ __($collection->calculated_current_year) }}
已在葡萄牙语翻译文件中配置:
"Commences": "Início",
期望输出Início 2022-09-06,但实际仍输出Commences 2022-09-06。
可行解决方案
方案1:拆分数据库返回字段(最直接)
修改SQL查询,不在数据库层拼接固定文本和变量,分开返回翻译键和日期:
SELECT "Commences" AS translation_key, commencement_date AS commencement_date ...
在Blade中先翻译固定文本,再拼接日期:
{{ __($collection->translation_key) }} {{ $collection->commencement_date }}
方案2:利用翻译文件的占位符功能(推荐)
在翻译文件中定义带占位符的条目:
// 葡萄牙语翻译文件(如resources/lang/pt/validation.php或自定义文件) "Commences": "Início :date",
控制器仅返回日期字段,或从拼接字符串中提取日期,在Blade中通过占位符填充:
{{ __("Commences", ['date' => $collection->commencement_date]) }}
若必须使用数据库返回的拼接字符串,可先拆分出日期:
@php $date = explode(' ', $collection->calculated_current_year)[1]; @endphp {{ __("Commences", ['date' => $date]) }}
方案3:自定义部分翻译助手函数(复杂场景适配)
如果无法修改数据库查询,可自定义助手函数提取固定文本进行翻译:
- 在
app/Helpers.php中添加函数:
function translate_partial($text) { // 定义需要匹配的翻译键列表 $keys = ['Commences']; foreach ($keys as $key) { if (str_contains($text, $key)) { return str_replace($key, __($key), $text); } } return $text; }
- 在Blade中调用:
{{ translate_partial($collection->calculated_current_year) }}
内容的提问来源于stack exchange,提问作者SupaMonkey
相关产品推荐
相关产品推荐

