Skip to content

Commit

Permalink
feat(globals): add elIf
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Aug 8, 2017
1 parent e0a2685 commit fb522ce
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/Globals/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,29 @@ const size = function (input) {
*/
const el = function (htmlStr, hash) {
return this.safe(htmlStr.replace(/\$([\w.-]+)/g, (match, group) => {
return _.get(hash, _.toPath(group))
return group === 'self' ? hash : _.get(hash, _.toPath(group))
}))
}

/**
* Return element only when the 3rd param
* is true.
*
* @method elIf
*
* @param {String} htmlStr
* @param {Object} hash
* @param {Boolean} ifResult
*
* @return {String}
*/
const elIf = function (htmlStr, hash, ifResult) {
if (!ifResult) {
return ''
}

return this.safe(htmlStr.replace(/\$([\w.-]+)/g, (match, group) => {
return group === 'self' ? hash : _.get(hash, _.toPath(group))
}))
}

Expand Down Expand Up @@ -276,6 +298,7 @@ module.exports = {
groupBy,
size,
el,
elIf,
camelCase,
upperCase,
upperFirst,
Expand Down
30 changes: 30 additions & 0 deletions test/unit/globals.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,34 @@ test.group('Globals', () => {
const output = Globals.urlEncode('http://foo.com?username=aman virk')
assert.equal(output, 'http://foo.com?username=aman%20virk')
})

test('self should return the entire hash back', (assert) => {
const context = {
safe (input) {
return input
}
}
const output = Globals.el.bind(context)('$self', 'Hello')
assert.equal(output, 'Hello')
})

test('render when if value is true', (assert) => {
const context = {
safe (input) {
return input
}
}
const output = Globals.elIf.bind(context)('Hello $name', { name: 'virk' }, true)
assert.equal(output, 'Hello virk')
})

test('return empty string when elIf boolean is false', (assert) => {
const context = {
safe (input) {
return input
}
}
const output = Globals.elIf.bind(context)('Hello $name', { name: 'virk' }, false)
assert.equal(output, '')
})
})

0 comments on commit fb522ce

Please sign in to comment.