|
| 1 | +# Asset |
| 2 | + |
| 3 | +The `Asset` helper is used to map asset names to versioned assets. |
| 4 | + |
| 5 | +This can be used to allow using a single, canonical name for an asset within |
| 6 | +your view scripts, while having that map to: |
| 7 | + |
| 8 | +- A versioned asset name, used to prevent browser caching. |
| 9 | +- A product of a build process (such as a CSS pre-processor, JS compiler, etc.) |
| 10 | + |
| 11 | +## Configuration and Basic Usage |
| 12 | + |
| 13 | +`Zend\View\Helper\Service\AssetFactory` checks the application configuration, |
| 14 | +making it possible to set up the resource map through your `module.config.php` |
| 15 | +or application configuration. As an example: |
| 16 | + |
| 17 | +```php |
| 18 | +'view_helper_config' => [ |
| 19 | + 'asset' => [ |
| 20 | + 'resource_map' => [ |
| 21 | + 'css/style.css' => 'css/style-3a97ff4ee3.css', |
| 22 | + 'js/vendor.js' => 'js/vendor-a507086eba.js', |
| 23 | + ], |
| 24 | + ], |
| 25 | +], |
| 26 | +``` |
| 27 | + |
| 28 | +Within your view script, you would reference the asset name: |
| 29 | + |
| 30 | +```php |
| 31 | +// Usable in any of your .phtml files: |
| 32 | +echo $this->asset('css/style.css'); |
| 33 | +``` |
| 34 | + |
| 35 | +which then emits the following output: |
| 36 | + |
| 37 | +```html |
| 38 | +css/style-3a97ff4ee3.css |
| 39 | +``` |
| 40 | + |
| 41 | +The first argument of the `asset` helper is the regular asset name, which will |
| 42 | +be replaced by the associated value defined in the `resource_map` of the |
| 43 | +configuration. |
| 44 | + |
| 45 | +> ### Exceptions |
| 46 | +> |
| 47 | +> When an `asset` key is specified but the `resource_map` is not provided or is not |
| 48 | +> an array, the helper will raise a `Zend\View\Exception\RuntimeException`. |
| 49 | +> |
| 50 | +> When you call the `asset` helper with a parameter not defined in your |
| 51 | +> `resource_map`, the helper will raise a `Zend\View\Exception\InvalidArgumentException`. |
| 52 | +
|
| 53 | +## Resource map in JSON file |
| 54 | + |
| 55 | +A number of build tools, such as gulp-rev and grunt-rev, will create a JSON |
| 56 | +resource map file such as `rev-manifest.json`: |
| 57 | + |
| 58 | +```javascript |
| 59 | +{ |
| 60 | + "css/style.css": "css/style-3a97ff4ee3.css", |
| 61 | + "js/vendor.js": "js/vendor-a507086eba.js" |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +You can incorporate these into your configuration manually by fetching and |
| 66 | +decoding the contents: |
| 67 | + |
| 68 | +```php |
| 69 | +'view_helper_config' => [ |
| 70 | + 'asset' => [ |
| 71 | + 'resource_map' => json_decode(file_get_contents('path/to/rev-manifest.json'), true), |
| 72 | + ], |
| 73 | +], |
| 74 | +``` |
| 75 | + |
| 76 | +If you have enabled configuration caching, these values _will also be cached_, |
| 77 | +meaning that the above operation will occur exactly once in your production |
| 78 | +configuration. |
0 commit comments