1

我正在使用 CodeIgniter 的库来更改网站上的语言。这就是我从控制器加载语言文件的方式:

$this->load->helper('language');
$this->load->helper('url');
$this->lang->load('custom','english');

但是我需要将一些数据从数据库传递到该语言文件(custom_lang.php),但我不知道如何?请指教...

4

2 回答 2

0

这是针对Codeigniter 2.0的。

您需要动态创建一个语言文件 (custom_lang.php)(例如,每当您更新数据库的语言内容时)

一:数据库布局

创建一个包含、、 、lang_token列的表,并像这样填充其字段:idcategorydescriptionlangtoken

    CREATE TABLE IF NOT EXISTS `lang_token` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `category` text NOT NULL,
      `description` text NOT NULL,
      `lang` text NOT NULL,
      `token` text NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

    INSERT INTO `lang_token` (`id`, `category`, `description`, `lang`, `token`) 
    VALUES
      (1, 'error', 'noMail', 'english', 'You must submit a valid email address'),
      (2, 'error', 'noUser', 'english', 'You must submit a username');

第二:关于CodeIgniter语言文件

CodeIgniter 将首先在您的应用程序/语言目录中查找,每种语言都应存储在其自己的文件夹中。确保您创建了英语或德语等子目录,例如application/language/english

第三:动态创建语言文件的控制器功能

关于 Codeigniter 语言文件:最好为给定文件中的所有消息使用公共前缀(类别),以避免与其他文件中类似命名的项目发生冲突。结构如下:$lang['category_description'] = “token”;

    function updatelangfile($my_lang){
        $this->db2->where('lang',$my_lang);
        $query=$this->db2->get('lang_token');

        $lang=array();
        $langstr="<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
                /**
                *
                * Created:  2014-05-31 by Vickel
                *
                * Description:  ".$my_lang." language file for general views
                *
                */"."\n\n\n";



        foreach ($query->result() as $row){
            //$lang['error_csrf'] = 'This form post did not pass our security checks.';
            $langstr.= "\$lang['".$row->category."_".$row->description."'] = \"$row->token\";"."\n";
        }
        write_file('./application/language/'.$my_lang.'/custom_lang.php', $langstr);

    }

最后注意事项:

  1. 每当您更改数据库时,都会调用该函数updatelangfile(‘english’)
  2. 不要忘记在 updatelangfile() 所在的控制器的构造函数中加载文件助手语言类:

    function __construct(){
        parent::__construct();
        $this->load->helper('file');
        $this->lang->load('custom', 'english');
    }
    
于 2014-05-31T17:35:35.483 回答
0

我猜您想处理翻译文本中的变量,例如“您有 XYZ 新消息”?

简单地在翻译文本中放置一些特定的标签,然后使用 str_replace 用所需的值填充它,比如“你有 %num_messages% 个新消息”。

在控制器中使用这个:

$parsed_text = str_replace ("%num_messages%", $msg_count, $input_translation_text);

然后将 $parsed_text 分配给模板/视图。

于 2012-08-09T23:19:42.707 回答