2013-04-20 22 views
6

我的組件包括一個Java腳本文件:添加語言常量到Joomla組件的JavaScript

$doc->addScript("/components/com_cam/js/cam.js"); 

我有一個我想與語言常量添加多個客戶端的消息,即

<?php echo JText::_('COM_CAM_SEND_LABEL'); ?> 

在你的前端php代碼很簡單,比如default.php,但是cam.js裏面的消息呢?

比如我的jQuery驗證:

 messages: { 
      cam: { 
       required: "Enter a label", 
       minlength: jQuery.format("At least {0} characters required!"), 
       maxlength: jQuery.format("Maximum {0} characters allowed!") 
      } 
     } 

,這是什麼最好的做法是什麼?

回答

5

在的Joomla! 2.5(自1.6我相信)有JText::script()它增加了支持將語言鍵添加到全球array(),以便您的Javascript可以訪問它們。

首先,在您的PHP中,您可以撥打JText::script('COM_MYCOMPONENT_MSG1');來獲取每個需要在Javascript中翻譯的字符串。

您可以在您的Javascript中使用內置的Joomla.JText._('COM_MYCOMPONENT_MSG1')來檢索它。

當你到了需要轉換大量字符串的地方時,你可能會發現只是在運行時解析javascript文件比較容易(效率低下的yada yada但後端管理員屏幕不是這麼大交易)。

/** 
* Parses a javascript file looking for JText keys and then loads them ready for use. 
* 
* @param string $jsFile Path to the javascript file. 
* 
* @return bool 
*/ 
public static function loadJSLanguageKeys($jsFile) 
{ 
    if (isset($jsFile)) 
    { 
     $jsFile = JPATH_SITE . $jsFile; 
    } 
    else 
    { 
     return false; 
    } 

    if ($jsContents = file_get_contents($jsFile)) 
    { 
     $languageKeys = array(); 
     preg_match_all('/Joomla\.JText\._\(\'(.*?)\'\)\)?/', $jsContents, $languageKeys); 
     $languageKeys = $languageKeys[1]; 

     foreach ($languageKeys as $lkey) 
     { 
      JText::script($lkey); 
     } 
    } 
} 
+0

謝謝!我只是用你的第一個解決方案,就像一個魅力。 – elk 2014-04-25 08:34:25

0

建立幫助函數來構建驗證消息並將其添加到head

喜歡的東西波紋管,只需編輯它以滿足您的需求

$messages = '(function ($) { 
    $.extend($.validator.messages, { 
      cam: { 
       required: "' . JText::_('COM_CAM_VALIDATION_REQUIRED') . '", 
       minlength: jQuery.format("' . JText::_('COM_CAM_VALIDATION_MINIMUM') . '"), 
       maxlength: jQuery.format("' . JText::_('COM_CAM_VALIDATION_MAXIMUM') . '") 
      } 
     }); 
}(jQuery));'; 

$doc = JFactory::getDocument(); 
$doc->addScriptDeclaration($messages);