dsrjs86444 2012-08-30 14:03
浏览 55
已采纳

CodeIgniter语言代码路由

I would like to add a language code segment to my URIs in CodeIgniter, but I'd like to somehow — possibly with routing — force the browser to stop interpreting a language code as a path.

I haven't yet successfully implemented any of the i18n libraries in my CodeIgniter install, and I'm fairly certain my problem is simple enough to solve without a library anyway.

The method I had in mind was simply to load the appropriate language files respective of the language code that appears in the URI.

For example

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

Here's the controller logic:

<?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);
    }
}

?>

Am I going about this the wrong way? If so, why? Please avoid canned responses.

  • 写回答

1条回答 默认 最新

  • dongzuo7166 2012-08-30 15:03
    关注

    I would go with CI routing:

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

    Then, your controller would look something like this:

    <?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);
    }
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿