Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,32 @@ string
})
```

### create multiple formats from a single date

By default the formatted date is output with the same key as the original date (so the original date gets replaced).

It can be useful to output a single date in more than one format. This can be achieved by:
- using the *array of objects* format for `dates`
- adding copies of date objects which include an `out_key` property

The following example re-uses the same `date` and outputs it in 2 formats named `dateNice`, `dateYear`.
```js
.use(dateFormatter({
dates: [
{
key: 'date',
format: 'MMMM DD, YYYY',
out_key: 'dateNice'
}, {
key: 'date',
format: 'YYYY',
out_key: 'dateYear'
}
]
})
```
(`out_key` can also be used to rename a date)

### format

Any date format that `moment` accepts, defaults to `MMMM DD, YYYY`
Expand Down
21 changes: 19 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function plugin(options) {
var dateKeys = DEFAULT_DATE_KEYS;
var normalizedDateKeys;
var formats;
var out_keys;

if (isString(options.dates)) {
dateKeys = [options.dates];
Expand All @@ -73,6 +74,9 @@ function plugin(options) {
if (normalizedDateKeys.formats) {
formats = normalizedDateKeys.formats;
}
if (normalizedDateKeys.out_keys) {
out_keys = normalizedDateKeys.out_keys;
}
}

return function (files, metalsmith, done) {
Expand All @@ -85,11 +89,15 @@ function plugin(options) {
transform(dateKeys, function (result, fKey, index) {
var time = result[fKey];
var localFormat = format;
var out_key = fKey;
if (formats && formats[index]) {
localFormat = formats[index];
}
if (out_keys && out_keys[index]) {
out_key = out_keys[index];
}
if (time) {
result[fKey] = moment.utc(time).format(localFormat);
result[out_key] = moment.utc(time).format(localFormat);
}
}, file);

Expand All @@ -108,6 +116,7 @@ function plugin(options) {
function normalizeDateKeys(dates) {
var keys = [];
var formats = [];
var out_keys = [];

dates.forEach(function (element) {
if (isString(element)) {
Expand All @@ -119,11 +128,19 @@ function normalizeDateKeys(dates) {
if (element.format) {
formats.push(element.format);
}
if (element.out_key) {
out_keys.push(element.out_key);
} else {
// out_keys isn't always defined but we need to keep the
// array indices in sync, so push something falsey
out_keys.push(undefined);
}
}
});

return {
keys: !isEmpty(keys) ? keys : null,
formats: !isEmpty(formats) ? formats : null
formats: !isEmpty(formats) ? formats : null,
out_keys: !isEmpty(out_keys) ? out_keys : null
};
}
Loading