Search code examples
codeigniter-2multilingual

How to return variable values in codeigniter language line strings?


To be more clear, none of these lines in default language's general_lang.php work:

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

or

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

I expect an output like Welcome, FirstName ( user_name ).

I followed the second (not accepted) answer at https://stackoverflow.com/a/10973668/315550.

The code I write in the view is:

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

I use codeigniter 2.


Solution

  • You will need to use php's sprintf function (http://php.net/manual/en/function.sprintf.php)

    Example from http://ellislab.com/forums/viewthread/145634/#749634:

    //in english
    $lang['unread_messages'] = "You have %1$s unread messages, %2$s";
    
    //in another language
    $lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
    
    $message = sprintf($this->lang->line(‘unread_messages’), $number, $name);