mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-15 04:10:40 -07:00
feature: date filter supports utc string now, fixes #49
This commit is contained in:
+11
-2
@@ -24,8 +24,13 @@ var filters = {
|
||||
'ceil': v => Math.ceil(v),
|
||||
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
|
||||
'date': (v, arg) => {
|
||||
if (v === 'now') v = new Date()
|
||||
return v instanceof Date ? strftime(v, arg) : ''
|
||||
let date = v
|
||||
if (v === 'now') {
|
||||
date = new Date()
|
||||
} else if (_.isString(v)) {
|
||||
date = new Date(v)
|
||||
}
|
||||
return isValidDate(date) ? strftime(date, arg) : v
|
||||
},
|
||||
'default': (v, arg) => isTruthy(v) ? v : arg,
|
||||
'divided_by': (v, arg) => Math.floor(v / arg),
|
||||
@@ -124,5 +129,9 @@ function registerAll (liquid) {
|
||||
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
|
||||
}
|
||||
|
||||
function isValidDate (date) {
|
||||
return date instanceof Date && !isNaN(date.getTime())
|
||||
}
|
||||
|
||||
registerAll.filters = filters
|
||||
module.exports = registerAll
|
||||
|
||||
+23
-17
@@ -2,24 +2,24 @@ const chai = require('chai')
|
||||
const chaiAsPromised = require('chai-as-promised')
|
||||
const expect = chai.expect
|
||||
var liquid = require('..')()
|
||||
var ctx
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
var ctx = {
|
||||
date: new Date(),
|
||||
foo: 'bar',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
},
|
||||
func: function () {},
|
||||
posts: [{
|
||||
category: 'foo'
|
||||
}, {
|
||||
category: 'bar'
|
||||
}]
|
||||
}
|
||||
|
||||
function test (src, dst) {
|
||||
ctx = {
|
||||
date: new Date(),
|
||||
foo: 'bar',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
},
|
||||
func: function () {},
|
||||
posts: [{
|
||||
category: 'foo'
|
||||
}, {
|
||||
category: 'bar'
|
||||
}]
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
||||
}
|
||||
|
||||
@@ -91,8 +91,14 @@ describe('filters', function () {
|
||||
it('should create a new Date when given "now"', function () {
|
||||
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
|
||||
})
|
||||
it('should render as empty string when invalid', function () {
|
||||
return test('{{ "" | date: "%Y"}}', '')
|
||||
it('should parse as Date when given UTC string', function () {
|
||||
return test('{{ "1991-02-22T00:00:00" | date: "%Y"}}', '1991')
|
||||
})
|
||||
it('should render string as string if not valid', function () {
|
||||
return test('{{ "foo" | date: "%Y"}}', 'foo')
|
||||
})
|
||||
it('should render object as string if not valid', function () {
|
||||
return test('{{ obj | date: "%Y"}}', '{"foo":"bar"}')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user