add language constants to Joomla component javascript

冷暖自知 提交于 2019-12-18 13:30:51

问题


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'); ?>

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

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

What is the best practice for this?


回答1:


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.

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

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

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



回答2:


Make a helper function to build validation messages and add it to the head.

Something like bellow, just edit it to suit your needs

$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);


来源:https://stackoverflow.com/questions/16122021/add-language-constants-to-joomla-component-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!