Skip to content

Commit

Permalink
feat(context): add safe method to ignore escaping
Browse files Browse the repository at this point in the history
calling safe before escape will make escape method ignore the escaping
  • Loading branch information
thetutlage committed Mar 28, 2017
1 parent 9be4fbe commit dfb7d46
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Context/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ const _ = require('lodash')
const debug = require('debug')('edge:context')
const escape = require('escape-html')

class Safe {
constructor (input) {
this._input = input
}

toString () {
return this._input
}
}

/**
* Runtime context used to run the compiled
* templates. View **locals**, **globals**,
Expand Down Expand Up @@ -217,6 +227,10 @@ class Context {
return _.get(hash, childs)
}

safe (input) {
return new Safe(input)
}

/**
* Escapes the input by sanitizing HTML.
*
Expand All @@ -227,6 +241,9 @@ class Context {
* @return {String}
*/
escape (input) {
if (input instanceof Safe) {
return input.toString()
}
return escape(input)
}

Expand Down
11 changes: 11 additions & 0 deletions test/unit/template.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -425,4 +425,15 @@ test.group('Template Runner', () => {
raw string
`)
})

test('calling escape after safe should not escape the content', (assert) => {
const loader = new Loader(path.join(__dirname, '../../test-helpers/views'))
const template = new Template(this.tags, {}, {}, loader)
const output = template.renderString('{{ someHtml() }}', {
someHtml () {
return this.safe('<h2> Hello </h2>')
}
})
assert.equal(output.trim(), '<h2> Hello </h2>')
})
})

0 comments on commit dfb7d46

Please sign in to comment.