Skip to content

Latest commit

 

History

History
99 lines (69 loc) · 2.58 KB

README.md

File metadata and controls

99 lines (69 loc) · 2.58 KB

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

  1. Add the package to your project.

    $ composer require netzstrategen/twig-asset
  2. 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());

JS

  1. Add the package to your project.

    $ npm install @netzstrategen/twig-asset --save
  2. Load the extension with your configuration in your project.

    const TwigAsset = require('@netzstrategen/twig-asset')({
      asset_path_document_root: __dirname,
    });
  3. Register the function in your Twig environment:

    for (const name in TwigAsset) {
      twig.extendFunction(name, TwigAsset[name]);
    } 

Third-party integrations

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.

  • asset_url_prefix (string, optional): URL prefix.

    Prefixed to the resulting asset URL; e.g., to serve all static assets on a separate domain.

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 to true.

    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):