@netzstrategen/twig-asset
v1.0.1
Published
asset() function for Twig.
Downloads
45
Maintainers
Keywords
Readme
Twig asset()
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.
Installation
PHP
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->addExtension(new TwigAsset());
JS
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]); }
Third-party integrations
Fractal
const twigAdapter = require('@netzstrategen/twig-drupal-fractal-adapter');
const instance = fractal.components.engine(twigAdapter);
instance.twig.extendFunction('asset', TwigAsset.asset);
Configuration
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.
Usage
<link rel="stylesheet" href="{{ asset('/path/from/root.css') }}">
yields:
<link rel="stylesheet" href="/path/from/root.css?v=1565339299">
Parameters
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">
Alternatives to this package
See Symfony for a more sophisticated solution (PHP only):