我有一个使用 Laravel 开发的网站,它支持使用本地化的多语言。
首先:我创建了语言文件夹及其文件 /resources/lang/en/message.php
<?php
return [
'page_title' => 'Welcome Page',
'welcome_message' => 'Hi, Welcome to this page',
'author_information' => 'My name is Sanjay. This blog is mine and we created this post for you to learn.',
];
/resources/lang/fr/messages.php
<?php
return [
'page_title' => 'Pagina de bienvenida',
'welcome_message' => 'Hola bienvenido a esta pagina',
'author_information' => 'Mi nombre es Sanjay. Este blog es mío y creamos esta publicación para que aprendas.',
];
其次:我在 web.php 文件中创建了应用程序路由
Route::get('/', [LocalizationController::class, "index"]);
Route::get('change/lang', [LocalizationController::class, "lang_change"])->name('LangChange');
第三:我创建了 LocalizationController 来管理语言更改
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class LocalizationController extends Controller
{
public function index()
{
return view('language');
}
public function lang_change(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
return view('language');
}
}
最后:可以使用由 LocalizationController 管理的下拉列表更改语言
<body>
<div class="container">
<div class="row" style="text-align: center;margin-top: 40px;">
<h2>How to Create Multi Language Website in Laravel - Online Web Tutor Blog</h2><br>
<div class="col-md-2 col-md-offset-3 text-right">
<strong>Select Language: </strong>
</div>
<div class="col-md-4">
<select class="form-control Langchange">
<option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
<option value="es" {{ session()->get('locale') == 'es' ? 'selected' : '' }}>Spanish</option>
</select>
</div>
<h1 style="margin-top: 80px;">{{ __('message.page_title') }}</h1>
<h2 style="margin-top: 80px;">{{ __('message.welcome_message') }}</h2>
<h3 style="margin-top: 80px;">{{ __('message.author_information') }}</h3>
</div>
</div>
</body>
<script type="text/javascript">
var url = "{{ route('LangChange') }}";
$(".Langchange").change(function(){
window.location.href = url + "?lang="+ $(this).val();
});
</script>
但是,当用户使用网站表单将数据插入数据库时,网站会准确显示用户插入的内容,网站有没有办法翻译用户输入?