Skip to content
58 changes: 58 additions & 0 deletions libraries/joomla/document/document.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,13 @@ class JDocument
*/
public $_script = array();

/**
* Array of scripts options
*
* @var array
*/
protected $scriptOptions = array();

/**
* Array of linked style sheets
*
Expand Down Expand Up @@ -514,6 +521,57 @@ public function addScriptDeclaration($content, $type = 'text/javascript')
return $this;
}

/**
* Add option for script
*
* @param string $key Name in Storage
* @param mixed $options Scrip options as array or string
* @param bool $merge Whether merge with existing (true) or replace (false)
*
* @return JDocument instance of $this to allow chaining
*
* @since 3.5
*/
public function addScriptOptions($key, $options, $merge = true)
{
if (empty($this->scriptOptions[$key]))
{
$this->scriptOptions[$key] = array();
}

if ($merge && is_array($options))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requires a blank line before the if statement according to codestyle.

{
$this->scriptOptions[$key] = array_merge($this->scriptOptions[$key], $options);
}
else
{
$this->scriptOptions[$key] = $options;
}

return $this;
}

/**
* Get script(s) options
*
* @param string $key Name in Storage
*
* @return array Options for given $key, or all script options
*
* @since 3.5
*/
public function getScriptOptions($key = null)
{
if ($key)
{
return (empty($this->scriptOptions[$key])) ? array() : $this->scriptOptions[$key];
}
else
{
return $this->scriptOptions;
}
}

/**
* Adds a linked stylesheet to the page
*
Expand Down
30 changes: 30 additions & 0 deletions libraries/joomla/document/renderer/html/head.php
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,36 @@ public function fetchHead($document)
$buffer .= '></script>' . $lnEnd;
}

// Generate scripts options
$scriptOptions = $document->getScriptOptions();

if (!empty($scriptOptions))
{
$buffer .= $tab . '<script type="text/javascript">' . $lnEnd;

// This is for full XHTML support.
if ($document->_mime != 'text/html')
{
$buffer .= $tab . $tab . '//<![CDATA[' . $lnEnd;
}

$pretyPrint = (JDEBUG && defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : false);
$jsonOptions = json_encode($scriptOptions, $pretyPrint);
$jsonOptions = $jsonOptions ? $jsonOptions : '{}';

// TODO: use .extend(Joomla.optionsStorage, options) when it will be safe
$buffer .= $tab . 'var Joomla = Joomla || {};' . $lnEnd;
$buffer .= $tab . 'Joomla.optionsStorage = ' . $jsonOptions . ';' . $lnEnd;

// See above note
if ($document->_mime != 'text/html')
{
$buffer .= $tab . $tab . '//]]>' . $lnEnd;
}

$buffer .= $tab . '</script>' . $lnEnd;
}

// Generate script declarations
foreach ($document->_script as $type => $content)
{
Expand Down