On this page
Caution
The documentation you are viewing is for an older version of this component.
Switch to the latest (v3) version.
Helpers
Asset
The Asset helper is used to map asset names to versioned assets.
This can be used to allow using a single, canonical name for an asset within your view scripts, while having that map to:
- A versioned asset name, used to prevent browser caching.
- A product of a build process (such as a CSS pre-processor, JS compiler, etc.)
Configuration and Basic Usage
Laminas\View\Helper\Service\AssetFactory checks the application configuration,
making it possible to set up the resource map through your module.config.php
or application configuration. As an example:
'view_helper_config' => [
'asset' => [
'resource_map' => [
'css/style.css' => 'css/style-3a97ff4ee3.css',
'js/vendor.js' => 'js/vendor-a507086eba.js',
],
],
],
Within your view script, you would reference the asset name:
// Usable in any of your .phtml files:
echo $this->asset('css/style.css');
which then emits the following output:
css/style-3a97ff4ee3.css
The first argument of the asset helper is the regular asset name, which will
be replaced by the associated value defined in the resource_map of the
configuration.
Exceptions
When an
assetkey is specified but theresource_mapis not provided or is not an array, the helper will raise aLaminas\View\Exception\RuntimeException.When you call the
assethelper with a parameter not defined in yourresource_map, the helper will raise aLaminas\View\Exception\InvalidArgumentException.
Resource map in JSON file
A number of build tools, such as gulp-rev and grunt-rev, will create a JSON
resource map file such as rev-manifest.json:
{
"css/style.css": "css/style-3a97ff4ee3.css",
"js/vendor.js": "js/vendor-a507086eba.js"
}
You can incorporate these into your configuration manually by fetching and decoding the contents:
'view_helper_config' => [
'asset' => [
'resource_map' => json_decode(file_get_contents('path/to/rev-manifest.json'), true),
],
],
If you have enabled configuration caching, these values will also be cached, meaning that the above operation will occur exactly once in your production configuration.