Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii: How to work with translate Yii::t() and hyperlinks

Tags:

yii

I have many lines similar to this in my code:

echo Yii::t('forms','Would you like to create a new item?');

where I want to hyperlink just around "create a new item", as an example.

Here are some alternatives that I've thought about:

  1. Split the URL into 2 translated strings, surrounded by a hyperlink:

    echo Yii::t('forms','Would you like to').' <a href="/new_item">'.Yii::t('forms','create a new item').'</a>?';
    
  2. Use placeholders, as described in the Yii documentation ( http://www.yiiframework.com/doc/guide/1.1/en/topics.i18n Although hyperlinks aren't given as an explicit example):

    echo Yii::t('forms','Would you like to {url}create a new item',array('{url}'=>"<a href='/new_item'>")).'</a>?';
    

There's probably an easier way to do this, but I've been unable to discover the preferred method...what's the best way to build translated strings that include URLs?

like image 433
ews2001 Avatar asked Dec 08 '22 21:12

ews2001


2 Answers

I suggest to you this solution:

echo Yii::t(
    'forms', 
    'Would you like to {link:create}create a new item{/link}?',
    array(
        '{link:create}'=>'<a href="/new_item">',
        '{/link}'=>'</a>',
    )
);

The benefit is if you want put id, class, onclick and more anything in a tag you can do it. and so the translate string in clear.
Note that create in {link:create} is just a ideal string that pointer to hyperlink string.

Another advanced sample:

echo Yii::t(
    'forms', 
    'Would you like to {link:create}create a new item{/link}? And you can {link:delete}delete the item{/link}.',
    array(
        '{link:create}'=>'<a href="/new_item" class="button">',
        '{link:delete}'=>'<a href="#" id="item-21" onclick="delete(21);">',
        '{/link}'=>'</a>',
    )
);
like image 97
Nabi K.A.Z. Avatar answered Feb 22 '23 18:02

Nabi K.A.Z.


The link may have different placement (beginning, middle or end) and label in the translated string depending on a target language. Therefore, you should use placeholder only for url:

echo Yii::t(
  'forms', 
  'Would you like to <a href="{url}">create a new item</a>?', 
  array('{url}' => '/new_item')
);
like image 25
galymzhan Avatar answered Feb 22 '23 18:02

galymzhan