Skip to content

Commit 6e6b398

Browse files
Merge pull request #918 from danwhite85/nunjucks-loader
Nunjucks loader to resolve Pattern Lab include paths
2 parents 12f3e07 + 32ec1c8 commit 6e6b398

File tree

3 files changed

+40
-76
lines changed

3 files changed

+40
-76
lines changed

packages/engine-nunjucks/README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ Level of Support is more or less full. Partial calls and lineage hunting are sup
1717

1818
## Extending the Nunjucks instance
1919

20-
To add custom filters or make customizations to the nunjucks instance, create a file named `patternlab-nunjucks-config.js` in the root of your Pattern Lab project. `patternlab-nunjucks-config.js` should export a function that takes two parameters. The first parameter is the nunjucks instance; the second is the nunjucks instance's environment.
20+
To add custom filters or make customizations to the nunjucks instance, create a file named `patternlab-nunjucks-config.js` in the root of your Pattern Lab project. `patternlab-nunjucks-config.js` should export a function with the Nunjucks environment as parameter.
2121

2222
```
23-
module.exports = function (nunjucks, env) {
23+
module.exports = function (env) {
2424
[YOUR CUSTOM CODE HERE]
2525
};
2626
```
@@ -30,7 +30,7 @@ Example: `patternlab-nunjucks-config.js` file that uses lodash and adds three cu
3030
var _shuffle = require('lodash/shuffle'),
3131
_take = require('lodash/take');
3232
33-
exports = module.exports = function (nunjucks, env) {
33+
exports = module.exports = function (env) {
3434
env.addFilter('shorten', function (str, count) {
3535
return str.slice(0, count || 5);
3636
});

packages/engine-nunjucks/lib/engine_nunjucks.js

Lines changed: 35 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -20,48 +20,43 @@
2020

2121
'use strict';
2222

23-
var fs = require('fs-extra'),
24-
path = require('path'),
25-
plPath = process.cwd(),
26-
plConfig = require(path.join(plPath, 'patternlab-config.json')),
27-
nunjucks = require('nunjucks'),
28-
env = nunjucks.configure(plConfig.paths.source.patterns),
29-
partialRegistry = [];
30-
31-
////////////////////////////
32-
// LOAD ANY USER NUNJUCKS CONFIGURATIONS
33-
////////////////////////////
23+
const fs = require('fs-extra');
24+
const path = require('path');
25+
const plPath = process.cwd();
26+
const plConfig = require(path.join(plPath, 'patternlab-config.json'));
27+
const nunjucks = require('nunjucks');
28+
const partialRegistry = [];
29+
30+
// Create Pattern Loader
31+
// Since Pattern Lab includes are not path based we need a custom loader for Nunjucks.
32+
function PatternLoader() {}
33+
34+
PatternLoader.prototype.getSource = function(name) {
35+
const fullPath = path.resolve(
36+
plConfig.paths.source.patterns,
37+
partialRegistry[name]
38+
);
39+
return {
40+
src: fs.readFileSync(fullPath, 'utf-8'),
41+
path: fullPath,
42+
};
43+
};
44+
45+
const env = new nunjucks.Environment(new PatternLoader());
46+
47+
// Load any user Defined configurations
3448
try {
35-
var nunjucksConfig = require(path.join(
49+
const nunjucksConfig = require(path.join(
3650
plPath,
3751
'patternlab-nunjucks-config.js'
3852
));
39-
if (typeof nunjucksConfig == 'function') {
40-
nunjucksConfig(nunjucks, env);
53+
if (typeof nunjucksConfig === 'function') {
54+
nunjucksConfig(env);
4155
}
4256
} catch (err) {}
4357

44-
////////////////////////////
45-
// HELPER FUNCTIONS
46-
// https://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string
47-
// Might do some research on the solution.
48-
////////////////////////////
49-
if (!String.prototype.replaceAll) {
50-
String.prototype.replaceAll = function(str1, str2, ignore) {
51-
return this.replace(
52-
new RegExp(
53-
str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, '\\$&'),
54-
ignore ? 'gi' : 'g'
55-
),
56-
typeof str2 == 'string' ? str2.replace(/\$/g, '$$$$') : str2
57-
);
58-
};
59-
}
60-
61-
////////////////////////////
62-
// NUNJUCKS ENGINE
63-
////////////////////////////
64-
var engine_nunjucks = {
58+
// Nunjucks Engine
59+
const engine_nunjucks = {
6560
engine: nunjucks,
6661
engineName: 'nunjucks',
6762
engineFileExtension: '.njk',
@@ -77,25 +72,24 @@ var engine_nunjucks = {
7772
// render it
7873
renderPattern: function renderPattern(pattern, data) {
7974
try {
80-
// replace pattern names with their full path so Nunjucks can find them.
81-
pattern.extendedTemplate = this.replacePartials(pattern);
82-
var result = nunjucks.renderString(pattern.extendedTemplate, data);
75+
const result = env.renderString(pattern.extendedTemplate, data);
8376
return Promise.resolve(result);
8477
} catch (err) {
8578
console.error('Failed to render pattern: ' + pattern.name);
79+
console.error(err);
8680
}
8781
},
8882

8983
// find and return any Nunjucks style includes/imports/extends within pattern
9084
findPartials: function findPartials(pattern) {
91-
var matches = pattern.template.match(this.findPartialsRE);
85+
const matches = pattern.template.match(this.findPartialsRE);
9286
return matches;
9387
},
9488

9589
// given a pattern, and a partial string, tease out the "pattern key" and return it.
9690
findPartial: function(partialString) {
9791
try {
98-
var partial = partialString.match(this.findPartialKeyRE)[1];
92+
let partial = partialString.match(this.findPartialKeyRE)[1];
9993
partial = partial.replace(/["']/g, '');
10094
return partial;
10195
} catch (err) {
@@ -116,38 +110,9 @@ var engine_nunjucks = {
116110
}
117111
},
118112

119-
replacePartials: function(pattern) {
120-
try {
121-
var partials = this.findPartials(pattern);
122-
if (partials !== null) {
123-
for (var i = 0; i < partials.length; i++) {
124-
// e.g. {% include "atoms-parent" %}
125-
var partialName = this.findPartial(partials[i]); // e.g. atoms-parent
126-
var partialFullPath = partialRegistry[partialName]; // e.g. 00-atoms/01-parent.njk
127-
var newPartial = partials[i].replaceAll(
128-
partialName,
129-
partialFullPath,
130-
true
131-
); // e.g. {% include "00-atoms/01-parent.njk" %}
132-
pattern.extendedTemplate = pattern.extendedTemplate.replaceAll(
133-
partials[i],
134-
newPartial,
135-
true
136-
);
137-
}
138-
}
139-
return pattern.extendedTemplate;
140-
} catch (err) {
141-
console.error(
142-
'Error occurred in replacing partial names with paths for patern: ' +
143-
pattern.name
144-
);
145-
}
146-
},
147-
148113
// still requires the mustache syntax because of the way PL handles lists
149114
findListItems: function(pattern) {
150-
var matches = pattern.template.match(this.findListItemsRE);
115+
const matches = pattern.template.match(this.findListItemsRE);
151116
return matches;
152117
},
153118

@@ -168,7 +133,6 @@ var engine_nunjucks = {
168133
fs.statSync(metaFilePath);
169134
} catch (err) {
170135
//not a file, so spawn it from the included file
171-
const localMetaFilePath = path.resolve(__dirname, '_meta/', fileName);
172136
const metaFileContent = fs.readFileSync(
173137
path.resolve(__dirname, '..', '_meta/', fileName),
174138
'utf8'

packages/engine-nunjucks/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
"deprecated": false,
88
"description": "The nunjucks PatternEngine for Pattern Lab / Node",
99
"dependencies": {
10-
"fs-extra": "5.0.0",
11-
"nunjucks": "3.0.1"
10+
"fs-extra": "7.0.0",
11+
"nunjucks": "3.1.3"
1212
},
1313
"engines": {
1414
"node": ">=4.0"

0 commit comments

Comments
 (0)