diff --git a/Readme.md b/Readme.md index 31dd2e5dcb..0d23723e16 100644 --- a/Readme.md +++ b/Readme.md @@ -25,6 +25,7 @@ * Route passing * View support (ejs, haml, sass, etc) * View partials + * View globals/helpers support * Full test coverage * Logger plugin with several formats * Upload size restrictions diff --git a/lib/express/plugins/view.js b/lib/express/plugins/view.js index 84c8764b9d..5620aceed4 100644 --- a/lib/express/plugins/view.js +++ b/lib/express/plugins/view.js @@ -19,7 +19,11 @@ var engines = {} * View cache. */ -var cache = { views: {}, partials: {}} +var cache = { views: {}, partials: {} } + +// View globals (helpers). + +var helpers = exports.helpers = {} /** * Cache view files where _type_ is @@ -153,6 +157,8 @@ exports.View = Plugin.extend({ layout = options.layout === undefined ? 'layout' : options.layout + options.locals = options.locals || {} + Object.merge(options.locals, helpers) options.filename = path if (set('cache view contents')) options.cache = true @@ -178,5 +184,4 @@ exports.View = Plugin.extend({ }) } } -}) - +}) \ No newline at end of file diff --git a/spec/fixtures/helpers-layout.html.haml b/spec/fixtures/helpers-layout.html.haml new file mode 100644 index 0000000000..0a90125685 --- /dev/null +++ b/spec/fixtures/helpers-layout.html.haml @@ -0,0 +1 @@ +Testing \ No newline at end of file diff --git a/spec/fixtures/helpers.html.haml b/spec/fixtures/helpers.html.haml new file mode 100644 index 0000000000..0d87fd6244 --- /dev/null +++ b/spec/fixtures/helpers.html.haml @@ -0,0 +1 @@ +%span= _('Hello world') \ No newline at end of file diff --git a/spec/fixtures/layout-helper.html.haml b/spec/fixtures/layout-helper.html.haml new file mode 100644 index 0000000000..7fbf911d47 --- /dev/null +++ b/spec/fixtures/layout-helper.html.haml @@ -0,0 +1 @@ +%span= _(body) \ No newline at end of file diff --git a/spec/spec.plugins.view.js b/spec/spec.plugins.view.js index c8cc8bdef4..5d2ae80503 100644 --- a/spec/spec.plugins.view.js +++ b/spec/spec.plugins.view.js @@ -1,5 +1,6 @@ ejs = require('ejs') +helpers = require('express/plugins/view').helpers describe 'Express' before_each @@ -213,6 +214,27 @@ describe 'Express' end end + describe 'when a global is set' + it 'should include the helper and translate the text in the view' + helpers._ = function(text){ + if (text == 'Hello world') return 'Hola mundo' + } + get('/', function(){ + this.render('helpers.html.haml', { layout: false }) + }) + get('/').body.should.include 'Hola mundo' + end + it 'should include the helper and translate the text in the layout' + helpers._ = function(text){ + if (text == 'Testing') return 'Probando' + } + get('/', function(){ + this.render('helpers-layout.html.haml', { layout: 'layout-helper' }) + }) + get('/').body.should.include 'Probando' + end + end + describe 'when engine cannot be found' it 'should throw an error' get('/', function(){