嗯,我沒有使用這個插件,但不得不做同樣的事情。我figuered指出,對於我的需要以下是最好的解決辦法:
在一個XML文件,我定義我的字符串(本例中爲xml/en/content.xml
):
<translations>
<translation id="hello_world"><![CDATA[Hello ##username##!]]></translation>
<translation id="how_are_you"><![CDATA[How are you?]]></translation>
</translations>
在我Localizer
I類初始化這些翻譯並將它們保存在一個數組中。 translate
函數從smarty獲取ID字符串,在其翻譯中搜索該ID並查找任何##string##
文本。這些##...##
將被替換爲已分配給smarty的變量。
class Localizer {
private static $translations = array();
public static function init($language) {
$temp_content = simplexml_load_file('xml/' . $language . '/content.xml');
foreach ($temp_content as $key => $value){
self::$translations[(string)$value['id']] = (string)$value;
}
}
public static function translate($params, $name, $smarty) {
$translation = '';
if(! is_null($name) && array_key_exists($name, self::$translations)) {
// get variables in translation text
$translation = self::$translations[$name];
preg_match_all('/##([^#]+)##/i', $translation, $vars, PREG_SET_ORDER);
// replace with assigned smarty values
foreach($vars as $var) {
$translation = str_replace($var[0], $smarty->getTemplateVars($var[1]), $translation);
}
}
return $translation;
}
}
現在你必須告訴smarty它應該使用哪個函數。這可能是你index.php
:
include('Localizer.class.php');
Localizer::init('en');
$smarty->registerPlugin('block', 'translate', array('Localizer', 'translate'), true);
要使用的翻譯,首先,我給你的用戶名:
$smarty->assign('username', $username);
在模板文件中:
{translate}hello_world{/translate}
希望這有助於問候奧地利:)
@Sascha Galley 我真的很感激 你的幫助。這很棒。但我不知道你在談論什麼Localizer類。我搜索了我的整個聰明的文件夾。沒有Localizer類。你能幫助我嗎?你使用另一個插件?也許那個? http://smarty.incutio.com/?page=LocalizerPlugin – Basti
@Basti它是我自己創建的一個類。編輯答案,希望現在清楚。 –
@Sascha Galley啊,好的。這就說得通了。我真的很抱歉如此愚蠢。我無法讓它運行。我現在做了以下幾點: 我在與Smarty.class.php相同的目錄中創建了Localizer.class.php。包含上面的代碼。那麼,現在我不知道在哪裏放置翻譯功能?我想它應該保證,模板中的功能將解決。那麼該怎麼做呢?我不能把一個函數放到function.translation.php中嗎? Sry,因爲沒有得到它... – Basti