2013-07-14 49 views
2

更清楚,沒有在默認語言的general_lang.php工作這些行:如何笨語言線串返回變量的值?

$lang['general_welcome_message'] = 'Welcome, %s (%s)'; 

$lang['general_welcome_message'] = 'Welcome, %1 (%2)'; 

我希望像Welcome, FirstName (user_name)輸出。

我跟着第二個(不接受)回答於https://stackoverflow.com/a/10973668/315550

我在視圖中編寫的代碼是:

<div id="welcome-box"> 
    <?php echo lang('general_welcome_message', 
       $this->session->userdata('user_firstname'), 
       $this->session->userdata('username') 
       ); 
    ?> 
</div> 

我用笨2.

回答

1

我擴展代碼CI_Lang類這樣的..

class MY_Lang extends CI_Lang { 
    function line($line = '', $swap = null) { 
     $loaded_line = parent::line($line); 
     // If swap if not given, just return the line from the language file (default codeigniter functionality.) 
     if(!$swap) return $loaded_line; 

     // If an array is given 
     if (is_array($swap)) { 
      // Explode on '%s' 
      $exploded_line = explode('%s', $loaded_line); 

      // Loop through each exploded line 
      foreach ($exploded_line as $key => $value) { 
       // Check if the $swap is set 
       if(isset($swap[$key])) { 
        // Append the swap variables 
        $exploded_line[$key] .= $swap[$key]; 
       } 
      } 
      // Return the implode of $exploded_line with appended swap variables 
      return implode('', $exploded_line); 
     } 
     // A string is given, just do a simple str_replace on the loaded line 
     else { 
      return str_replace('%s', $swap, $loaded_line); 
     } 
    } 
} 

即,在你的語言文件:

$lang['foo'] = 'Thanks, %s. Your %s has been changed.' 

在哪裏,無論你想用它(控制器/瀏覽等)

echo $this->lang->line('foo', array('Charlie', 'password')); 

會產生

Thanks, Charlie. Your password has been changed. 

該處理單 '互換'以及多個

而且它不會破壞任何現有的呼叫$this->lang->line

+0

非常整潔。謝謝 ! –