我参与了一个 Laravel 项目,为了通过 Ajax 调用和 Jquery 获取 div 的内容,我确实喜欢 Blade 模板中的内容:
results[k].items.map((result,index) => (
$(".kf_opponents_wrap2").append(
'<div class="kf_opponents_wrap">\
<h6 class="kf_h4">\
<em>'+((result.fixture.status.elapsed == null || result.fixture.status.elapsed == 90) ? getMatchTime(result.fixture.timestamp) : result.fixture.status.elapsed)+'</em>\
</h6>\
<div class="kf_opponents_dec">\
<span><img src="'+result.teams.home.logo+'" alt=""></span>\
<div class="text">\
<h6><a href="#">'+result.teams.home.name+'</a></h6>\
</div>\
......
)
到目前为止一切都很好,并且使用 Ajax 调用正确显示了 div,下一个问题是如何在 Append 中进行翻译并在 Laravel 函数中使用 javascript 变量而不是 php 变量
echo __('.....');
<a href="#">echo __('+result.teams.home.name+');</a> // I know is wrong because is confusion between client side and server side.
我尝试使用https://github.com/rmariuzzo/Laravel-JS-Localization但根本不适合我。
我的问题是如何在 javascript 中使用 Laravel 翻译,使用 javascript 变量内部或其他方式使用 php 或从数据库获取翻译?有什么想法吗?
您可以创建一个端点来返回所有翻译密钥并在 JS 应用程序上使用它
use Illuminate\Support\Facades\File;
public function getAllTranslations()
{
$languages = ['en', 'es', 'fr']; // Add more languages as needed
$translations = [];
foreach ($languages as $lang) {
$translations[$lang] = [];
// Assuming your translations are in the resources/lang directory
$files = File::allFiles(resource_path("lang/$lang"));
foreach ($files as $file) {
$filename = pathinfo($file)['filename'];
$translations[$lang][$filename] = trans($filename, [], $lang);
}
}
return response()->json($translations);
}
这在 routers/api.php 上
use App\Http\Controllers\YourController;
Route::get('/translations', [YourController::class, 'getAllTranslations']);