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

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

本文介绍了将语言常量添加到Joomla组件javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件包括一个Java脚本文件:

My component includes a java script file:

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

我想添加一些客户端消息,它们带有语言常量,即

I have several client side messages that I'd like to add with language constants, i.e.

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

在您的前端PHP代码(如default.php)中足够容易,但是cam.js中的消息呢?

Easy enough in your front end php code like default.php but what about messages inside cam.js?

例如我的jquery验证:

Such as my jquery validation:

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

最佳做法是什么?

推荐答案

在Joomla中! 2.5(自1.6起,我相信)有 JText::script() ,它增加了对将语言键添加到全局变量的支持array(),以便您的Javascript可以访问它们.

In Joomla! 2.5 (since 1.6 I believe) there is JText::script() which adds support for adding language keys to a global array() so that your Javascript can access them.

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

First up, in your PHP you can call JText::script('COM_MYCOMPONENT_MSG1'); for each string you need translated in your Javascript.

您可以使用Javascript中的内置Joomla.JText._('COM_MYCOMPONENT_MSG1')进行检索.

The you can use the built-in Joomla.JText._('COM_MYCOMPONENT_MSG1') in your Javascript to retrieve it.

当您到达要转换许多字符串的地步时,您可能会发现在运行时解析javascript文件更容易(效率低下的yada yada,但对于后端管理屏幕而言,没什么大不了的).

When you get to the point where there a lots of strings to be converted you may find it easier to just parse the javascript file at run time (in-efficient yada yada but for back-end admin screens not such a big deal).

/**
 * 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);
        }
    }
}

这篇关于将语言常量添加到Joomla组件javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:29