Skip to content

Instantly share code, notes, and snippets.

@laurenashpole
Created September 25, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laurenashpole/2426da02553fe5d66009a77cad40f6c1 to your computer and use it in GitHub Desktop.
Save laurenashpole/2426da02553fe5d66009a77cad40f6c1 to your computer and use it in GitHub Desktop.
A custom Swig tag for getting versioned asset paths.
let assets = require('../../public/assets.json');
module.exports = function (swig) {
swig.setTag('asset', _parse, _compile, false, true);
};
let _parse = function (str, line, parser) {
parser.on('*', function (token) {
let match = token.match.match(/^["'](.*?)["']$/);
let assetPath = match ? match[1] : null;
if (assetPath) {
let asset = assets[assetPath] || assetPath;
this.out.push(asset);
}
});
return true;
};
let _compile = function (compiler, args) {
if (!args || !args[0]) {
throw new Error('The asset tag expects a filename as a string');
}
let assetPath = args[0].startsWith('/') ? args[0] : '/' + args[0];
return `_output +="${assetPath}";`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment