Skip to content

Commit

Permalink
Fixed package name and implementation, added JS port. (#1)
Browse files Browse the repository at this point in the history
Co-Authored-By: Fabian Marz <[email protected]>
  • Loading branch information
sun and fabianmarz authored Aug 16, 2019
1 parent 3af89d6 commit e613548
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 60 deletions.
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# 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.
```sh
$ composer require netzstrategen/twig-asset
```

2. Add the extension and configuration to your Twig environment.
```php
<?php
use Netzstrategen\TwigAsset\TwigExtension as TwigAsset;
$twig->addGlobal('asset_path_document_root', '<path/to/templates>');
$twig->addExtension(new TwigAsset());
```
### JS
1. Add the package to your project.
```sh
$ npm install @netzstrategen/twig-asset --save
```
2. Load the extension with your configuration in your project.
```js
const TwigAsset = require('@netzstrategen/twig-asset')({
asset_path_document_root: __dirname,
});
3. Register the function in your Twig environment:
```js
for (const name in TwigAsset) {
twig.extendFunction(name, TwigAsset[name]);
}
```
### Third-party integrations
#### [Fractal](https://fractal.build)
```js
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
```twig
<link rel="stylesheet" href="{{ asset('/path/from/root.css') }}">
```
yields:
```html
<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:
```twig
<link rel="stylesheet" href="{{ asset('/path/from/root.css', false) }}">
```
yields:
```html
<link rel="stylesheet" href="/path/from/root.css">
```
## Alternatives to this package
See Symfony for a more sophisticated solution (PHP only):
- [Symfony Asset Component](https://symfony.com/doc/current/components/asset.html)
- [Symfony Encore](https://symfony.com/doc/current/frontend/encore/versioning.html)
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cue/twig_extensions",
"description": "Fractal integration for Drupal.",
"name": "netzstrategen/twig-asset",
"description": "asset() function for Twig.",
"license": "GPL-2.0+",
"authors": [
{
Expand All @@ -14,7 +14,7 @@
],
"autoload": {
"psr-4": {
"Cue\\twig_extensions\\": "src/"
"Netzstrategen\\TwigAsset\\": "php/"
}
}
}
31 changes: 31 additions & 0 deletions js/functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';

const fs = require('fs');
const path = require('path');
const querystring = require('querystring');

module.exports = (config = {}) => {

config = Object.assign({
add_version: true,
}, config);

return {
asset: (asset_path) => {
if (!config.asset_path_document_root) {
return asset_path;
}
const absolute_path = path.join(config.asset_path_document_root, asset_path);
if (config.add_version && fs.existsSync(absolute_path)) {
const stats = fs.statSync(absolute_path);
const filemtime = Math.floor(stats.mtimeMs / 1000);
const query_string = querystring.stringify({
v: filemtime,
});
asset_path += `?${query_string}`;
}
return asset_path;
}
}

}
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@netzstrategen/twig-asset",
"version": "1.0.0",
"description": "asset() function for Twig.",
"main": "js/functions.js",
"files": ["js/*"],
"repository": {
"type": "git",
"url": "git+https://github.com/netzstrategen/twig-asset.git"
},
"author": "Fabian Marz <[email protected]>",
"contributors": [
"Daniel Kudwien <[email protected]>"
],
"license": "GPL-2.0+",
"bugs": {
"url": "https://github.com/netzstrategen/twig-asset/issues"
},
"homepage": "https://github.com/netzstrategen/twig-asset#readme"
}
53 changes: 53 additions & 0 deletions php/TwigExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/**
* @file
* Contains \Netzstrategen\TwigAsset\TwigExtension.
*/

namespace Netzstrategen\TwigAsset;

use Twig_Environment;
use Twig_Extension;
use Twig_ExtensionInterface;
use Twig_SimpleFunction;

class TwigExtension extends Twig_Extension implements Twig_ExtensionInterface {

public function getFunctions() {
return [
new Twig_SimpleFunction('asset', [$this, 'getAssetPath'], [
'needs_environment' => TRUE,
]),
];
}

/**
* Appends the modification time to the given asset file path.
*
* @param Twig_Environment $env
* The current Twig environment.
* @param string $path
* The path to the asset file relative to the Twig environment.
* @param bool $add_version
* Whether to append the file modification time. Defaults to TRUE.
*
* @return string
*/
public static function getAssetPath(Twig_Environment $env, string $path, bool $add_version = TRUE): string {
$globals = $env->getGlobals();
if (!empty($globals['asset_path_document_root'])) {
$asset_root = realpath($globals['asset_path_document_root']);
$absolute_path = $asset_root . '/' . $path;

if ($add_version && file_exists($absolute_path)) {
$query_string = http_build_query([
'v' => filemtime($absolute_path),
]);
$path .= '?' . $query_string;
}
}
return $path;
}

}
57 changes: 0 additions & 57 deletions src/TwigExtensions.php

This file was deleted.

0 comments on commit e613548

Please sign in to comment.