Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add language constants to Joomla component javascript

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?

like image 380
Tom Avatar asked Apr 20 '13 15:04

Tom


1 Answers

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);
        }
    }
}
like image 160
Craig Avatar answered Oct 18 '22 00:10

Craig