将语言常量添加到Joomla组件javascript中

时间:2013-04-20 15:27:11

标签: joomla joomla2.5

我的组件包含一个java脚本文件:

$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!")
            }
        }

最佳做法是什么?

2 个答案:

答案 0 :(得分:5)

在Joomla! 2.5(自1.6以来我认为)JText::script()增加了对全局array()添加语言密钥的支持,以便您的Javascript可以访问它们。

首先,在PHP中,您可以为需要在Javascript中翻译的每个字符串调用JText::script('COM_MYCOMPONENT_MSG1');

您可以使用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);
        }
    }
}

答案 1 :(得分:0)

创建一个帮助函数来构建验证消息并将其添加到head

像bellow这样的东西,只需编辑它以满足您的需求

$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);
相关问题