diff --git a/README.md b/README.md index e4e7048..2e5f3b8 100644 --- a/README.md +++ b/README.md @@ -41,4 +41,27 @@ In your code, you can mark an asset group for inclusion using `Assets::group()` At this point, you can use `Assets::get()` to retrieve all assets that were added by section. - $assets->get('body'); // Retrieves any asset in the `body` section within all required groups. \ No newline at end of file + $assets->get('body'); // Retrieves any asset in the `body` section within all required groups. + +## Passing Javascript variables + +You can pipeline server-side information into client-side Javascript variables using the `pass` method: + + $this->assets->pass([ + 'route' => [ + 'name' => Route::name($this->request->route()), + 'controller' => strtolower($this->request->controller()), + 'action' => $this->request->action() + ], + 'url' => [ + 'base' => URL::base(), + 'media' => URL::base().Media::uri('/').'/' + ], + 'environment' => Kohana::$environment + ]); + +When you use `Assets::get()` to retrieve all the `head` assets, data will be encoded like this: + + + +In Javascript, your variables are set and ready to use within the `window.pass` global variable. diff --git a/classes/Yuriko/Assets.php b/classes/Yuriko/Assets.php index 51f8a0e..5c87919 100644 --- a/classes/Yuriko/Assets.php +++ b/classes/Yuriko/Assets.php @@ -24,6 +24,11 @@ public static function factory(Object $config = NULL) */ protected $_requested = array(); + /** + * @var array Collection of variables of pass to JavaScript + */ + protected $_pass = array(); + protected $_config; public function __construct(ArrayObject $config = NULL) @@ -49,6 +54,28 @@ public function groups(array $names) return $this; } + /** + * Pass variable to JavaScript through 'head' section + * + * @param array $pairs An array that will be converted into JSON eventually + * @param bool $reset Reset previous passes? + * @return $this + */ + public function pass(array $pairs, $reset = FALSE) + { + if ($reset) + { + $this->_pass = array(); + } + + foreach ($pairs as $key => $value) + { + $this->_pass[$key] = $value; + } + + return $this; + } + public function get($section = NULL) { $assets = array(); @@ -76,6 +103,13 @@ public function get($section = NULL) usort($assets, array($this, '_sort_assets')); $array = array(); + + // Prepend pass-through variables to JavaScript + if ($section == 'head') + { + $array[] = $this->_escape_pass(); + } + foreach ($assets as $asset) { $attributes = Arr::get($asset, 4, array()); @@ -98,6 +132,17 @@ public function get($section = NULL) return $array; } + /** + * Escape pass-through variables as a JavaScript inline block + * + * @return string + */ + protected function _escape_pass() + { + $escaped = 'window.pass = '.json_encode($this->_pass).';'; + return ''; + } + /** * Custom sorting method for assets based on 'weight' key */