【问题标题】:How to generate url to routes with two languages in Laravel如何在 Laravel 中使用两种语言生成路由的 url
【发布时间】:2016-11-29 10:34:21
【问题描述】:

基于此 thread 我尝试为我的网站实现额外的英语语言,默认为法语并且不使用任何前缀,所以像www.website.com 这样的东西@ 切换到英语将是@ 987654323@,我想要联系页面的网址,例如英文版和法文版的www.website.com/en/contactwww.website.com/contact

我当前的 routes.php

if (Request::segment(1) == 'en') {
    App::setLocale(Request::segment(1));
    Config::set('app.locale_prefix', Request::segment(1));
}
else {
    App::setLocale('fr');
    Config::set('app.locale_prefix', '');
}

Route::group(array('prefix' => Config::get('app.locale_prefix')), function()
{
    Route::get(
        '/',
        function () {
            //return "main page - ".App::getLocale();
            return view('index');
        }
    );
    Route::get(
        '/contact/',
        function () {
            return view('contact');
        });
});

我的头文件中切换语言的标志图标是

    @if (Lang::locale() == 'fr')
        <a href="{{ url('/en/' . Request::segment(1)) }}"><img src="{{asset('images/GB.png')}}"></a>
    @elseif (strcasecmp(Request::segment(1), 'en') == 0 && Request::segment(2) != NULL)
        <a href="{{ url( Request::segment(2)) }}"><img src="{{asset('images/FR.png')}}"></a>
    @else
        <a href="{{ url( '/') }}"><img src="{{asset('images/FR.png')}}"></a>
    @endif

以及我生成网址的方式

<a class="block-title" href="{{ (strcasecmp(Request::route()->getPrefix(), '/en') == 0) ? url('en/contact') : url('/contact') }}">CONTACT</a>

我想知道一种更简洁的方法来生成这些,以及如何让英文主页 url 成为 www.website.com/en/ 而不是 www.website.com/en

非常感谢!

【问题讨论】:

    标签: php laravel laravel-5 localization routes


    【解决方案1】:

    生成 URL 的最佳方法是:

    首先,给你的路线命名:

    //this route is called 'contact_route'
    Route::get('/contact/', ['as' => 'contact_route', function () 
    {
        return view('contact');
    }]);
    

    路由是使用语言环境和前缀动态构建的,但是一旦定义了路由并为其命名,您就可以使用route helper 为路由创建一个 URL:route('contact_route')

    你的例子会变成:

    <a class="block-title" href="{{ route('contact_route') }}">CONTACT</a>
    

    您可以在docs了解更多命名路线

    至于尾部斜杠,默认的 Laravel .htaccess 文件,删除了 url 末尾的所有斜杠,规则如下:

    RewriteRule ^(.*)/$ $1 [L,R=301]
    

    这将捕获所有(.*) 从开头^ 到斜线/$ 之前的结尾,并将其替换为捕获的内容。所以,如果你想添加一个斜杠,可能你应该编辑.htaccess文件

    【讨论】:

    • 非常感谢!我将更详细地了解此 route() 的工作原理。
    • @adaba :不客气。我刚刚添加了几个文档链接:)
    【解决方案2】:

    您可以使用路由组

    全英文

    Route::group(['prefix' => 'en', 'namespace' => '\English'], function () {
      Route::get('contact', [
        'as'   => 'en.contact',
        'uses' => 'ContactController@contactUs',
      ]);
    });
    

    所有法国航线

    Route::group(['prefix' => 'fr', 'namespace' => '\French'], function () {
      Route::get('contact', [
        'as'   => 'fr.contact',
        'uses' => 'ContactController@contactUs',
      ]);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 2013-01-16
      • 2015-10-26
      • 1970-01-01
      • 2019-05-02
      • 2017-03-18
      • 2014-03-31
      • 2011-01-09
      • 2020-03-04
      相关资源
      最近更新 更多