A simple asset function for Twig, which appends the file modification time of the referenced asset file to ensure the browser reloads the resource when it changes. (cache invalidation)
This repository holds the extension for PHP and JS.
-
Add the package to your project.
$ composer require netzstrategen/twig-asset
-
Add the extension and configuration to your Twig environment.
<?php use Netzstrategen\TwigAsset\TwigExtension as TwigAsset; $twig->addGlobal('asset_path_document_root', '<path/to/templates>'); $twig->addGlobal('asset_url_prefix', 'https://static.example.com'); // optional CDN integration $twig->addExtension(new TwigAsset());
-
Add the package to your project.
$ npm install @netzstrategen/twig-asset --save
-
Load the extension with your configuration in your project.
const TwigAsset = require('@netzstrategen/twig-asset')({ asset_path_document_root: __dirname, });
-
Register the function in your Twig environment:
for (const name in TwigAsset) { twig.extendFunction(name, TwigAsset[name]); }
const twigAdapter = require('@netzstrategen/twig-drupal-fractal-adapter');
const instance = fractal.components.engine(twigAdapter);
instance.twig.extendFunction('asset', TwigAsset.asset);
-
asset_path_document_root
(string, required): Path to the document root.Acts as a base path. The path passed to the asset() function will be appended to this base path in order to retrieve the file's modification time.
-
asset_url_prefix
(string, optional): URL prefix.Prefixed to the resulting asset URL; e.g., to serve all static assets on a separate domain.
<link rel="stylesheet" href="{{ asset('/path/from/root.css') }}">
yields:
<link rel="stylesheet" href="/path/from/root.css?v=1565339299">
-
add_version
(bool, optional): Whether to append the file modification time. Defaults totrue
.Example:
<link rel="stylesheet" href="{{ asset('/path/from/root.css', false) }}">
yields:
<link rel="stylesheet" href="/path/from/root.css">
See Symfony for a more sophisticated solution (PHP only):