使用不带domain.com/language/的Laravel5进行本地化 [英] Localization with Laravel5 without domain.com/language/

查看:49
本文介绍了使用不带domain.com/language/的Laravel5进行本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Laravel建立一个边做边学的项目,并且要面对本地化问题.我在论坛上看到有可用的语言包,但我认为(假设)Laravel提供了我想要的东西,尽管我还不知道在哪里.

I'm setting up a learning-by-doing project with Laravel and facing localization. I've seen on the forum that there's a language-package available but I think (assume) Laravel provides something I'm looking for, although I don't know where to look yet.

基本上,我有一个使用刀刃渲染的视图.没什么特别的.我尝试使用App::setLocale('nl')来获取翻译,效果很好.

Basically I have a view which renders using blade. Nothing special. I've tried to use App::setLocale('nl') to get the translations, which works nice.

然后,在我的视线变得混乱之后,我开始使用@extends()@section()在一些文件中放入一些东西,我注意到每个文件都必须调用App::setLocale()才能获取翻译.这似乎有点不方便...

Then, after my view got a bit messy I started to put some stuff in several files using @extends() and @section(), I noticed each file has to call App::setLocale() in order to fetch the translations. This seems a bit unhandy...

是否可以为所有视图和子视图的请求的整个生命周期设置语言? (如果没有Laravel,我将使用$_SESSION[]$_COOKIE或数据库将其存储,然后在index.php文件中进行设置)

Is there a way to set the language for the entire life-cycle of a request for all views and subviews? (Without Laravel I would store this using $_SESSION[], $_COOKIE or in the database and then setting it in the index.php-file)

我不打算为荷兰语版本开发www.domain.com/nl/stuff,为英语版开发www.domain.com/en/stuff之类的东西.因为我正在创建某种Web应用程序,所以不需要SEO.

I'm not trying to develop something like www.domain.com/nl/stuff for the Dutch version and www.domain.com/en/stuff for the English version. There's no need for SEO since I'm creating a sort-of web-app.

有什么想法在哪里找到的吗?

Any idea where to find this?

P.s.我知道我可以在/config/app.php中设置语言,但我也想提供一个语言下拉菜单,供用户选择所需的语言. (可用语言的数量可能会增加)

P.s. I know I can set the language in /config/app.php but I would also like to provide a language-dropdown for users to select their desired language. (Where the number of available languages could grow)

推荐答案

您不应在视图内部设置语言环境.您应该在呈现所有视图之前 进行此操作.例如,在中间件

You shouldn't set the locale inside the view. You should do it before all the views get rendered. For example in a middleware

例如这样的东西:

class LangMiddleware {

/**
 * Run the request filter.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next)
    {
        if(Input::has('lang')){
            App::setLocale(Input::get('lang'));
        }

        return $next($request);
    }
}

然后将其注册为全局中间件,您可以对请求进行?lang=en设置区域设置.这只是一个示例,您可以做任何您想做的...;)

And then register this as global middleware and you can do ?lang=en on the request to set the locale. This is just an example you can do whatever you want... ;)

这篇关于使用不带domain.com/language/的Laravel5进行本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆