Created
October 18, 2012 12:03
-
-
Save willmorgan/3911381 to your computer and use it in GitHub Desktop.
JavaScriptConfig: A utility class to add in configuration information for JS files in the head tag.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* JavaScriptConfig | |
* A utility class to add in configuration information for JS files in the head | |
* section, directly from PHP and json_encode with Requirements. | |
* Used with SilverStripe 2.4+ | |
* @author @willmorgan | |
*/ | |
class JavaScriptConfig { | |
protected static | |
$config_name = 'JS_CONFIG', | |
$configs = array(), | |
$has_written = false, | |
$written_configs = array(); | |
static function add($paramName, $paramVal) { | |
self::$configs[$paramName] = $paramVal; | |
if(self::$has_written) { | |
self::insert(); | |
} | |
} | |
static function insert() { | |
if(!self::$has_written) { | |
if(empty(self::$configs)) { | |
$json = '{}'; | |
} | |
else { | |
$json = Convert::array2json(self::$configs); | |
} | |
$html = '<script>window.'.self::$config_name.' = ' . $json . ';</script>'; | |
self::$has_written = true; | |
} | |
else { | |
$js = ''; | |
foreach(self::$configs as $paramName => $paramVal) { | |
$js .= self::$config_name . '[\''.$paramName.'\'] = ' . json_encode($paramVal) . ";\n"; | |
} | |
$html = '<script>' . $js .'</script>'; | |
} | |
self::$written_configs = array_merge(self::$written_configs, self::$configs); | |
self::$configs = array(); | |
Requirements::insertHeadTags($html); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment