CodeIgniter语言代码路由

时间:2012-08-30 14:03:13

标签: php codeigniter url-routing

我想在CodeIgniter中为我的URI添加语言代码段,但我想以某种方式 - 可能使用路由 - 强制浏览器停止将语言代码解释为路径。

我还没有在我的CodeIgniter安装中成功实现任何i18n库,而且我相当确定我的问题很简单,无论如何都可以解决。

我想到的方法只是加载相应语言代码的相应语言文件。

例如

http://example.com/about        // Default language
http://example.com/sv/about     // Load Swedish language

这是控制器逻辑:

<?php
//  ** Update **
//  The following updated code works, as long as the language code appears
//  at the end of the URI, e.g, http://example.com/about/sv
//
//  Ideally, I would like the language code segment to always appear first.
//
//  There is also the problem of keeping the language selected while
//  navigating around the site…

class Pages extends CI_Controller {
    public function view ($page = 'home') {

        if (!file_exists('application/views/pages/'.$page.'.php'))
            show_404();

        $uri = explode("/", $_SERVER['REQUEST_URI']);
        $lang_code = end($uri);

        $data['title'] = $lang_code;

        switch ($lang_code) {
            case "sv": $the_language = "swedish"; break;
            case "no": $the_language = "norwegian"; break;
            default: $the_language = "english";
        }

        $this->lang->load('general',$the_language);
        $this->load->view('templates/header', $data);
        $this->load->view('pages/'.$page, $data);
        $this->load->view('templates/footer', $data);
    }
}

?>

我是以错误的方式来做这件事的吗?如果是这样,为什么?请避免预设回复。

1 个答案:

答案 0 :(得分:2)

我会选择CI路由:

$route['([a-z]+)/([a-z]+)'] = "pages/view/$2";

然后,您的控制器看起来像这样:

<?php if (! defined('BASEPATH')) exit('No direct script access');

class Pages extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->language = $this->uri->segment(1);
}

function view($page = 'home')
{
    /* other stuff */
    $this->lang->load('general',$this->language);
    $this->load->view('templates/header', $data);
    $this->load->view('pages/'.$page, $data);
    $this->load->view('templates/footer', $data);
}

}