Compare commits

..

3 Commits

Author SHA1 Message Date
Tyler Kellen
a7dfb3a8be bump version 2012-11-27 09:25:42 -06:00
Tyler Kellen
e800693475 Merge pull request #8 from tebriel/master
amdWrapper and prettify options
2012-11-27 07:24:05 -08:00
Chris Moultrie
ac6580aa2c Added an amdWrapper option and a prettify option 2012-11-26 13:01:28 -05:00
31 changed files with 438 additions and 690 deletions

2
.gitattributes vendored
View File

@ -1,2 +0,0 @@
# Automatically normalize line endings for all text-based files
* text=crlf

View File

@ -1,13 +0,0 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"boss": true,
"eqnull": true,
"node": true
}

View File

@ -1,6 +1,3 @@
language: node_js language: node_js
node_js: node_js:
- "0.8" - 0.8
- "0.10"
before_script:
- npm install -g grunt-cli

View File

@ -1,5 +1,4 @@
Tim Branyen (http://tbranyen.com) Tim Branyen (http://tbranyen.com)
Tyler Kellen (http://goingslowly.com/) Tyler Kellen (http://goingslowly.com/)
Chris Talkington (http://christalkington.com/) Chris Talkington (http://christalkington.com/)
Larry Davis (http://lazd.net/) Larry Davis (http://lazd.net/)
Adrien Antoine (http://adriantoine.com/)

View File

@ -1,30 +1,8 @@
v0.5.1: v0.3.2:
date: 2013-07-14 date: 2012-10-13
changes: changes:
- Display filepath when fails to compile. - Add prettify option
v0.5.0: - Add amdWrapper option
date: 2013-03-06
changes:
- When `namespace` is false and `amd` is true, return templates directly from AMD wrapper.
- Rename `amdwrapper` option to `amd` to match grunt-contrib-handlebars.
v0.4.1:
date: 2013-02-15
changes:
- First official release for Grunt 0.4.0.
v0.4.1rc7:
date: 2012-01-29
changes:
- Correct line endings for lodash output on windows.
v0.4.0rc7:
date: 2013-01-23
changes:
- Updating grunt/gruntplugin dependencies to rc7.
- Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
v0.4.0rc5:
date: 2013-01-09
changes:
- Updating to work with grunt v0.4.0rc5.
- Switching to this.files api.
v0.3.1: v0.3.1:
date: 2012-10-12 date: 2012-10-12
changes: changes:
@ -44,4 +22,4 @@ v0.2.2:
v0.2.0: v0.2.0:
date: 2012-08-10 date: 2012-08-10
changes: changes:
- Refactored from grunt-contrib into individual repo. - Refactored from grunt-contrib into individual repo.

View File

@ -1 +0,0 @@
Please see the [Contributing to grunt](http://gruntjs.com/contributing) guide for information on contributing to this project.

View File

@ -1,163 +0,0 @@
/*
* grunt-contrib-jst
* http://gruntjs.com/
*
* Copyright (c) 2013 Tim Branyen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
test: ['tmp']
},
// Configuration to be run (and then tested).
jst: {
compile: {
options: {
templateSettings: {
variable: 'obj'
}
},
files: {
"tmp/jst.js": ["test/fixtures/template.html"]
}
},
pretty_amd: {
options: {
templateSettings: {
variable: 'obj'
},
prettify: true,
amd: true
},
files: {
"tmp/pretty_amd.js": ["test/fixtures/template.html"]
}
},
prettify: {
options: {
templateSettings: {
variable: 'obj'
},
prettify: true
},
files: {
"tmp/pretty.js": ["test/fixtures/template.html"]
}
},
amd_wrapper: {
options: {
templateSettings: {
variable: 'obj'
},
amd:true
},
files: {
"tmp/amd_wrapper.js": ["test/fixtures/template.html"]
}
},
amd_wrapper_no_ns: {
options: {
templateSettings: {
variable: 'obj'
},
amd:true,
namespace:false
},
files: {
"tmp/amd_wrapper_no_ns.js": ["test/fixtures/template.html"]
}
},
uglyfile: {
options: {
templateSettings: {
variable: 'obj'
},
},
files: {
"tmp/uglyfile.js": ["test/fixtures/*bad-filename*"]
}
},
ns_nested: {
options: {
templateSettings: {
variable: 'obj'
},
namespace: "MyApp.JST.Main"
},
files: {
"tmp/ns_nested.js": ["test/fixtures/template.html"]
}
},
ns_nested_this: {
options: {
templateSettings: {
variable: 'obj'
},
namespace: "this.MyApp.JST.Main"
},
files: {
"tmp/ns_nested_this.js": ["test/fixtures/template.html"]
}
},
process_content: {
options: {
templateSettings: {
variable: 'obj'
},
processContent: function (src) {
return src.replace(/(^\s+|\s+$)/gm, '');
}
},
files: {
"tmp/process_content.js": ["test/fixtures/indent_template.html"]
}
},
local_scope: {
files: {
"tmp/local_scope.js": ["test/fixtures/template_local_scope.html"]
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.loadNpmTasks('grunt-contrib-clean');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'jst', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test', 'build-contrib']);
};

View File

@ -1,4 +1,4 @@
Copyright (c) 2013 Tim Branyen, contributors Copyright (c) 2012 Tim Branyen, contributors
Permission is hereby granted, free of charge, to any person Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation obtaining a copy of this software and associated documentation

284
README.md
View File

@ -1,168 +1,116 @@
# grunt-contrib-jst v0.5.1 [![Build Status](https://travis-ci.org/gruntjs/grunt-contrib-jst.png?branch=master)](https://travis-ci.org/gruntjs/grunt-contrib-jst) # grunt-contrib-jst [![Build Status](https://secure.travis-ci.org/gruntjs/grunt-contrib-jst.png?branch=master)](http://travis-ci.org/gruntjs/grunt-contrib-jst)
> Precompile Underscore templates to JST file. > Compile underscore templates to JST file.
## Getting Started
Install this grunt plugin next to your project's [grunt.js gruntfile][getting_started] with: `npm install grunt-contrib-jst`
## Getting Started
This plugin requires Grunt `~0.4.0` Then add this line to your project's `grunt.js` gruntfile:
If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command: ```javascript
grunt.loadNpmTasks('grunt-contrib-jst');
```shell ```
npm install grunt-contrib-jst --save-dev
``` [grunt]: https://github.com/gruntjs/grunt
[getting_started]: https://github.com/gruntjs/grunt/blob/master/docs/getting_started.md
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
### Overview
```js
grunt.loadNpmTasks('grunt-contrib-jst'); This task compiles Underscore compatible templates into functions that can be concatenated and minified with existing source files.
```
Inside your `grunt.js` file, add a section named `jst`. This section specifies the files to compile and the options passed to [underscore.template](http://underscorejs.org/#template).
*This plugin was designed to work with Grunt 0.4.x. If you're still using grunt v0.3.x it's strongly recommended that [you upgrade](http://gruntjs.com/upgrading-from-0.3-to-0.4), but in case you can't please use [v0.3.1](https://github.com/gruntjs/grunt-contrib-jst/tree/grunt-0.3-stable).*
#### Parameters
##### files ```object```
## Jst task
_Run this task with the `grunt jst` command._ This defines what files this task will process and should contain key:value pairs.
Task targets, files and options may be specified according to the grunt [Configuring tasks](http://gruntjs.com/configuring-tasks) guide. The key (destination) should be an unique filepath (supports [grunt.template](https://github.com/gruntjs/grunt/blob/master/docs/api_template.md)) and the value (source) should be a filepath or an array of filepaths (supports [minimatch](https://github.com/isaacs/minimatch)).
_This plugin uses [the Lo-Dash library](http://lodash.com/) to generate JavaScript template functions. Some developers generate template functions dynamically during development. If you are doing so, please be aware that the functions generated by this plugin may differ from those created at run-time. For instance, [the Underscore.js library](http://underscorejs.org/) will throw an exception if templates reference undefined top-level values, while Lo-Dash will silently insert an empty string in their place._ Note: Values are precompiled to the namespaced JST array in the order passed.
### Options
##### options ```object```
#### separator
Type: `String` This controls how this task (and its helpers) operate and should contain key:value pairs, see options below.
Default: linefeed + linefeed
#### Options
Concatenated files will be joined on this string.
##### namespace ```string```
#### namespace
Type: `String` The namespace in which the precompiled templates will be asssigned (default is JST). *Use dot notation (e.g. App.Templates) for nested namespaces.*
Default: 'JST'
Example:
The namespace in which the precompiled templates will be assigned. Use dot notation (e.g. App.Templates) for nested namespaces or false for no namespace wrapping. When false with amd option set true, templates will be returned directly from the AMD wrapper. ``` javascript
options: {
#### processName namespace: 'JST'
Type: `function` }
Default: null ```
This option accepts a function which takes one argument (the template filepath) and returns a string which will be used as the key for the precompiled template object. The example below stores all templates on the default JST namespace in capital letters. ##### prettify ```boolean```
```js When doing a quick once-over of your compiled template file, it's nice to see
options: { an easy-to-read format that has one line per template. This will accomplish
processName: function(filename) { that.
return filename.toUpperCase();
} Example:
} ```javascript
``` options: {
prettify: true
#### templateSettings }
Type: `Object` ```
Default: null
##### amdWrapper ```boolean```
The settings passed to underscore when compiling templates.
With Require.js and a pre-compiled template.js you want the templates to be
```js wrapped in a define. This will wrap the output in:
jst: { ``` javascript
compile: { define(function() {
options: { //Templates
templateSettings: { return this["NAMESPACE"];
interpolate : /\{\{(.+?)\}\}/g });
} ```
},
files: { Example:
"path/to/compiled/templates.js": ["path/to/source/**/*.html"] ``` javascript
} options: {
} amdWrapper: true
} }
``` ```
#### prettify ##### processName ```function```
Type: `boolean`
Default: false This option accepts a function which takes one argument (the template filepath) and returns a string which will be used as the key for the precompiled template object. The example below stores all templates on the default JST namespace in capital letters.
When doing a quick once-over of your compiled template file, it's nice to see ``` javascript
an easy-to-read format that has one line per template. This will accomplish options: {
that. processName: function(filename) {
return filename.toUpperCase();
```js }
options: { }
prettify: true ```
}
``` ##### templateSettings ```object```
#### amd The settings passed to underscore when compiling templates.
Type: `boolean`
Default: false #### Config Examples
Wraps the output file with an AMD define function and returns the compiled template namespace unless namespace has been explicitly set to false in which case the template function will be returned directly. ``` javascript
jst: {
```js compile: {
define(function() { options: {
//...// templateSettings: {
return this['[template namespace]']; interpolate : /\{\{(.+?)\}\}/g
}); }
``` },
files: {
Example: "path/to/compiled/templates.js": ["path/to/source/**/*.html"]
```js }
options: { }
amd: true }
} ```
```
--
#### processContent
Type: `function` *Task submitted by [Tim Branyen](http://github.com/tbranyen).*
This option accepts a function which takes one argument (the file content) and
returns a string which will be used as template string.
The example below strips whitespace characters from the beginning and the end of
each line.
```js
options: {
processContent: function(src) {
return src.replace(/(^\s+|\s+$)/gm, '');
}
}
```
### Usage Examples
```js
jst: {
compile: {
options: {
templateSettings: {
interpolate : /\{\{(.+?)\}\}/g
}
},
files: {
"path/to/compiled/templates.js": ["path/to/source/**/*.html"]
}
}
}
```
Note that the `interpolate: /\{\{(.+?)\}\}/g` setting above is simply an example of overwriting lodash's default interpolation. If you want to parse templates with the default `_.template` behavior (i.e. using `<div><%= this.id %></div>`), there's no need to overwrite `templateSettings.interpolate`.
## Release History
* 2013-07-14v0.5.1Display filepath when fails to compile.
* 2013-03-06v0.5.0When `namespace` is false and `amd` is true, return templates directly from AMD wrapper. Rename `amdwrapper` option to `amd` to match grunt-contrib-handlebars.
* 2013-02-15v0.4.1First official release for Grunt 0.4.0.
* 2012-01-29v0.4.1rc7Correct line endings for lodash output on windows.
* 2013-01-23v0.4.0rc7Updating grunt/gruntplugin dependencies to rc7. Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
* 2013-01-09v0.4.0rc5Updating to work with grunt v0.4.0rc5. Switching to this.files api.
* 2012-10-12v0.3.1Rename grunt-contrib-lib dep to grunt-lib-contrib.
* 2012-08-23v0.3.0Options no longer accepted from global config key.
* 2012-08-16v0.2.3Support for nested namespaces.
* 2012-08-12v0.2.2Added processName functionality & escaping single quotes in filenames.
* 2012-08-10v0.2.0Refactored from grunt-contrib into individual repo.
---
Task submitted by [Tim Branyen](http://tbranyen.com)
*This file was generated on Sat Oct 19 2013 14:22:27.*

0
docs/examples.md Normal file
View File

View File

@ -1,17 +0,0 @@
# Usage Examples
```js
jst: {
compile: {
options: {
templateSettings: {
interpolate : /\{\{(.+?)\}\}/g
}
},
files: {
"path/to/compiled/templates.js": ["path/to/source/**/*.html"]
}
}
}
```
Note that the `interpolate: /\{\{(.+?)\}\}/g` setting above is simply an example of overwriting lodash's default interpolation. If you want to parse templates with the default `_.template` behavior (i.e. using `<div><%= this.id %></div>`), there's no need to overwrite `templateSettings.interpolate`.

View File

@ -1,98 +0,0 @@
# Options
## separator
Type: `String`
Default: linefeed + linefeed
Concatenated files will be joined on this string.
## namespace
Type: `String`
Default: 'JST'
The namespace in which the precompiled templates will be assigned. Use dot notation (e.g. App.Templates) for nested namespaces or false for no namespace wrapping. When false with amd option set true, templates will be returned directly from the AMD wrapper.
## processName
Type: `function`
Default: null
This option accepts a function which takes one argument (the template filepath) and returns a string which will be used as the key for the precompiled template object. The example below stores all templates on the default JST namespace in capital letters.
```js
options: {
processName: function(filename) {
return filename.toUpperCase();
}
}
```
## templateSettings
Type: `Object`
Default: null
The settings passed to underscore when compiling templates.
```js
jst: {
compile: {
options: {
templateSettings: {
interpolate : /\{\{(.+?)\}\}/g
}
},
files: {
"path/to/compiled/templates.js": ["path/to/source/**/*.html"]
}
}
}
```
## prettify
Type: `boolean`
Default: false
When doing a quick once-over of your compiled template file, it's nice to see
an easy-to-read format that has one line per template. This will accomplish
that.
```js
options: {
prettify: true
}
```
## amd
Type: `boolean`
Default: false
Wraps the output file with an AMD define function and returns the compiled template namespace unless namespace has been explicitly set to false in which case the template function will be returned directly.
```js
define(function() {
//...//
return this['[template namespace]'];
});
```
Example:
```js
options: {
amd: true
}
```
## processContent
Type: `function`
This option accepts a function which takes one argument (the file content) and
returns a string which will be used as template string.
The example below strips whitespace characters from the beginning and the end of
each line.
```js
options: {
processContent: function(src) {
return src.replace(/(^\s+|\s+$)/gm, '');
}
}
```

View File

@ -1,3 +0,0 @@
Task targets, files and options may be specified according to the grunt [Configuring tasks](http://gruntjs.com/configuring-tasks) guide.
_This plugin uses [the Lo-Dash library](http://lodash.com/) to generate JavaScript template functions. Some developers generate template functions dynamically during development. If you are doing so, please be aware that the functions generated by this plugin may differ from those created at run-time. For instance, [the Underscore.js library](http://underscorejs.org/) will throw an exception if templates reference undefined top-level values, while Lo-Dash will silently insert an empty string in their place._

87
docs/options.md Normal file
View File

@ -0,0 +1,87 @@
##### files ```object```
This defines what files this task will process and should contain key:value pairs.
The key (destination) should be an unique filepath (supports [grunt.template](https://github.com/gruntjs/grunt/blob/master/docs/api_template.md)) and the value (source) should be a filepath or an array of filepaths (supports [minimatch](https://github.com/isaacs/minimatch)).
Note: Values are precompiled to the namespaced JST array in the order passed.
##### options ```object```
This controls how this task (and its helpers) operate and should contain key:value pairs, see options below.
#### Options
##### namespace ```string```
The namespace in which the precompiled templates will be asssigned (default is JST). *Use dot notation (e.g. App.Templates) for nested namespaces.*
Example:
```js
options: {
namespace: 'JST'
}
```
##### prettify ```boolean```
When doing a quick once-over of your compiled template file, it's nice to see
an easy-to-read format that has one line per template. This will accomplish
that.
Example:
```javascript
options: {
prettify: true
}
```
##### amdWrapper ```boolean```
With Require.js and a pre-compiled template.js you want the templates to be
wrapped in a define. This will wrap the output in:
``` javascript
define(function() {
//Templates
return this["NAMESPACE"];
});
```
Example:
``` javascript
options: {
amdWrapper: true
}
```
##### processName ```function```
This option accepts a function which takes one argument (the template filepath) and returns a string which will be used as the key for the precompiled template object. The example below stores all templates on the default JST namespace in capital letters.
```js
options: {
processName: function(filename) {
return filename.toUpperCase();
}
}
```
##### templateSettings ```object```
The settings passed to underscore when compiling templates.
#### Config Examples
```js
jst: {
compile: {
options: {
templateSettings: {
interpolate : /\{\{(.+?)\}\}/g
}
},
files: {
"path/to/compiled/templates.js": ["path/to/source/**/*.html"]
}
}
}
```

View File

@ -1 +1 @@
*This plugin was designed to work with Grunt 0.4.x. If you're still using grunt v0.3.x it's strongly recommended that [you upgrade](http://gruntjs.com/upgrading-from-0.3-to-0.4), but in case you can't please use [v0.3.1](https://github.com/gruntjs/grunt-contrib-jst/tree/grunt-0.3-stable).* This task compiles Underscore compatible templates into functions that can be concatenated and minified with existing source files.

114
grunt.js Normal file
View File

@ -0,0 +1,114 @@
/*
* grunt-contrib-jst
* http://gruntjs.com/
*
* Copyright (c) 2012 Tim Branyen, contributors
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
lint: {
all: ['grunt.js', 'tasks/*.js', '<config:nodeunit.tasks>']
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
es5: true
}
},
// Before generating any new files, remove any previously-created files.
clean: {
test: ['tmp']
},
// Configuration to be run (and then tested).
jst: {
compile: {
files: {
"tmp/jst.js": ["test/fixtures/template.html"]
}
},
pretty_amd: {
options: {
prettify: true,
amdWrapper: true
},
files: {
"tmp/pretty_amd.js": ["test/fixtures/template.html"]
}
},
prettify: {
options: {
prettify: true
},
files: {
"tmp/pretty.js": ["test/fixtures/template.html"]
}
},
amd_wrapper: {
options: {
amdWrapper:true
},
files: {
"tmp/amd_wrapper.js": ["test/fixtures/template.html"]
}
},
uglyfile: {
files: {
"tmp/uglyfile.js": ["test/fixtures/*bad-filename*"]
}
},
ns_nested: {
options: {
namespace: "MyApp.JST.Main"
},
files: {
"tmp/ns_nested.js": ["test/fixtures/template.html"]
}
},
ns_nested_this: {
options: {
namespace: "this.MyApp.JST.Main"
},
files: {
"tmp/ns_nested_this.js": ["test/fixtures/template.html"]
}
}
},
// Unit tests.
nodeunit: {
tasks: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// The clean plugin helps in testing.
grunt.loadNpmTasks('grunt-contrib-clean');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.renameTask('test', 'nodeunit');
grunt.registerTask('test', 'clean jst nodeunit');
// By default, lint and run all tests.
grunt.registerTask('default', 'lint test');
};

View File

@ -1,50 +1,41 @@
{ {
"name": "grunt-contrib-jst", "name": "grunt-contrib-jst",
"description": "Precompile Underscore templates to JST file.", "description": "Precompile Underscore templates to JST file.",
"version": "0.5.1", "version": "0.3.2",
"homepage": "https://github.com/gruntjs/grunt-contrib-jst", "homepage": "https://github.com/gruntjs/grunt-contrib-jst",
"author": { "author": {
"name": "Grunt Team", "name": "Grunt Team",
"url": "http://gruntjs.com/" "url": "http://gruntjs.com/"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/gruntjs/grunt-contrib-jst.git" "url": "git://github.com/gruntjs/grunt-contrib-jst.git"
}, },
"bugs": { "bugs": {
"url": "https://github.com/gruntjs/grunt-contrib-jst/issues" "url": "https://github.com/gruntjs/grunt-contrib-jst/issues"
}, },
"licenses": [ "licenses": [
{ {
"type": "MIT", "type": "MIT",
"url": "https://github.com/gruntjs/grunt-contrib-jst/blob/master/LICENSE-MIT" "url": "https://github.com/gruntjs/grunt-contrib-jst/blob/master/LICENSE-MIT"
} }
], ],
"engines": { "main": "grunt.js",
"node": ">= 0.8.0" "engines": {
}, "node": ">= 0.8.0"
"scripts": { },
"test": "grunt test" "scripts": {
}, "test": "grunt test"
"dependencies": { },
"lodash": "~1.0.0", "dependencies": {
"grunt-lib-contrib": "~0.5.1" "underscore": "~1.3.3",
}, "grunt-lib-contrib": "~0.3.0"
"devDependencies": { },
"grunt-contrib-jshint": "~0.6.0", "devDependencies": {
"grunt-contrib-nodeunit": "~0.2.0", "grunt": "~0.3.15",
"grunt-contrib-clean": "~0.4.1", "grunt-contrib-clean": "~0.3.0"
"grunt-contrib-internal": "~0.4.5", },
"grunt": "~0.4.0" "keywords": [
}, "gruntplugin"
"peerDependencies": { ]
"grunt": "~0.4.0" }
},
"keywords": [
"gruntplugin"
],
"files": [
"tasks",
"LICENSE-MIT"
]
}

View File

@ -2,94 +2,72 @@
* grunt-contrib-jst * grunt-contrib-jst
* http://gruntjs.com/ * http://gruntjs.com/
* *
* Copyright (c) 2013 Tim Branyen, contributors * Copyright (c) 2012 Tim Branyen, contributors
* Licensed under the MIT license. * Licensed under the MIT license.
*/ */
'use strict';
module.exports = function(grunt) { module.exports = function(grunt) {
"use strict";
var _ = require('lodash'); var _ = require("underscore");
var helpers = require('grunt-lib-contrib').init(grunt);
// filename conversion for templates // filename conversion for templates
var defaultProcessName = function(name) { return name; }; var defaultProcessName = function(name) { return name; };
grunt.registerMultiTask('jst', 'Compile underscore templates to JST file', function() { grunt.registerMultiTask("jst", "Compile underscore templates to JST file", function() {
var lf = grunt.util.linefeed;
var helpers = require('grunt-lib-contrib').init(grunt); var helpers = require("grunt-lib-contrib").init(grunt);
var options = this.options({ var options = helpers.options(this, {namespace: "JST", templateSettings: {}});
namespace: 'JST',
templateSettings: {},
processContent: function (src) { return src; },
separator: lf + lf,
template: _.template
});
// assign filename transformation functions // assign filename transformation functions
var processName = options.processName || defaultProcessName; var processName = options.processName || defaultProcessName;
var nsInfo; grunt.verbose.writeflags(options, "Options");
if (options.namespace !== false) {
nsInfo = helpers.getNamespaceDeclaration(options.namespace);
}
this.files.forEach(function(f) { // TODO: ditch this when grunt v0.4 is released
var output = f.src.filter(function(filepath) { this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) { var compiled, srcFiles, src, filename;
grunt.log.warn('Source file "' + filepath + '" not found.'); var output = [];
return false; var nsInfo = helpers.getNamespaceDeclaration(options.namespace);
} else {
return true; this.files.forEach(function(files) {
} srcFiles = grunt.file.expandFiles(files.src);
}) srcFiles.forEach(function(file) {
.map(function(filepath) { src = grunt.file.read(file);
var src = options.processContent(grunt.file.read(filepath));
var compiled, filename;
try { try {
compiled = options.template(src, false, options.templateSettings).source; compiled = _.template(src, false, options.templateSettings).source;
} catch (e) { } catch (e) {
grunt.log.error(e); grunt.log.error(e);
grunt.fail.warn('JST "' + filepath + '" failed to compile.'); grunt.fail.warn("JST failed to compile.");
} }
if (options.prettify) { if (options.prettify) {
compiled = compiled.replace(new RegExp('\n', 'g'), ''); compiled = compiled.replace(/\n+/g, '');
} }
filename = processName(filepath); filename = processName(file);
output.push(nsInfo.namespace+"["+JSON.stringify(filename)+"] = "+compiled+";");
if (options.amd && options.namespace === false) {
return 'return ' + compiled;
}
return nsInfo.namespace+'['+JSON.stringify(filename)+'] = '+compiled+';';
}); });
if (output.length < 1) { if(output.length > 0) {
grunt.log.warn('Destination not written because compiled files were empty.'); output.unshift(nsInfo.declaration);
} else { if (options.amdWrapper) {
if (options.namespace !== false) { if (options.prettify) {
output.unshift(nsInfo.declaration); output.forEach(function(line, index) {
output[index] = " " + line;
});
}
output.unshift("define(function(){");
output.push(" return " + nsInfo.namespace + ";\n});");
} }
if (options.amd) { grunt.file.write(files.dest, output.join("\n\n"));
if (options.prettify) { grunt.log.writeln("File '" + files.dest + "' created.");
output.forEach(function(line, index) {
output[index] = " " + line;
});
}
output.unshift("define(function(){");
if (options.namespace !== false) {
// Namespace has not been explicitly set to false; the AMD
// wrapper will return the object containing the template.
output.push(" return " + nsInfo.namespace + ";");
}
output.push("});");
}
grunt.file.write(f.dest, output.join(grunt.util.normalizelf(options.separator)));
grunt.log.writeln('File "' + f.dest + '" created.');
} }
}); });
}); });
}; };

View File

@ -2,14 +2,15 @@ define(function(){
this["JST"] = this["JST"] || {}; this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/template.html"] = function(obj) { this["JST"]["test/fixtures/template.html"] = function(obj){
var __t, __p = '', __e = _.escape; var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
__p += '<head><title>' + with(obj||{}){
((__t = ( obj.title )) == null ? '' : __t) + __p+='<head><title>'+
( title )+
'</title></head>'; '</title></head>';
return __p }
return __p;
}; };
return this["JST"]; return this["JST"];
}); });

View File

@ -1,11 +0,0 @@
define(function(){
return function(obj) {
var __t, __p = '', __e = _.escape;
__p += '<head><title>' +
((__t = ( obj.title )) == null ? '' : __t) +
'</title></head>';
return __p
}
});

View File

@ -1,9 +1,11 @@
this["JST"] = this["JST"] || {}; this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/template.html"] = function(obj) { this["JST"]["test/fixtures/template.html"] = function(obj){
var __t, __p = '', __e = _.escape; var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
__p += '<head><title>' + with(obj||{}){
((__t = ( obj.title )) == null ? '' : __t) + __p+='<head><title>'+
( title )+
'</title></head>'; '</title></head>';
return __p }
return __p;
}; };

View File

@ -1,13 +0,0 @@
this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/template_local_scope.html"] = function(obj) {
obj || (obj = {});
var __t, __p = '', __e = _.escape;
with (obj) {
__p += '<head><title>' +
((__t = ( title )) == null ? '' : __t) +
'</title></head>';
}
return __p
};

View File

@ -2,10 +2,12 @@ this["MyApp"] = this["MyApp"] || {};
this["MyApp"]["JST"] = this["MyApp"]["JST"] || {}; this["MyApp"]["JST"] = this["MyApp"]["JST"] || {};
this["MyApp"]["JST"]["Main"] = this["MyApp"]["JST"]["Main"] || {}; this["MyApp"]["JST"]["Main"] = this["MyApp"]["JST"]["Main"] || {};
this["MyApp"]["JST"]["Main"]["test/fixtures/template.html"] = function(obj) { this["MyApp"]["JST"]["Main"]["test/fixtures/template.html"] = function(obj){
var __t, __p = '', __e = _.escape; var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
__p += '<head><title>' + with(obj||{}){
((__t = ( obj.title )) == null ? '' : __t) + __p+='<head><title>'+
( title )+
'</title></head>'; '</title></head>';
return __p }
return __p;
}; };

View File

@ -1,3 +1,3 @@
this["JST"] = this["JST"] || {}; this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/template.html"] = function(obj) {var __t, __p = '', __e = _.escape;__p += '<head><title>' +((__t = ( obj.title )) == null ? '' : __t) +'</title></head>';return __p}; this["JST"]["test/fixtures/template.html"] = function(obj){var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};with(obj||{}){__p+='<head><title>'+( title )+'</title></head>';}return __p;};

View File

@ -2,8 +2,7 @@ define(function(){
this["JST"] = this["JST"] || {}; this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/template.html"] = function(obj) {var __t, __p = '', __e = _.escape;__p += '<head><title>' +((__t = ( obj.title )) == null ? '' : __t) +'</title></head>';return __p}; this["JST"]["test/fixtures/template.html"] = function(obj){var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};with(obj||{}){__p+='<head><title>'+( title )+'</title></head>';}return __p;};
return this["JST"]; return this["JST"];
}); });

View File

@ -1,9 +0,0 @@
this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/indent_template.html"] = function(obj) {
var __t, __p = '', __e = _.escape;
__p += '<div>\n<div>\n<div>\n' +
((__t = ( obj.name )) == null ? '' : __t) +
'\n</div>\n</div>\n</div>';
return __p
};

View File

@ -1,7 +1,9 @@
this["JST"] = this["JST"] || {}; this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/it's-a-bad-filename.html"] = function(obj) { this["JST"]["test/fixtures/it's-a-bad-filename.html"] = function(obj){
var __t, __p = '', __e = _.escape; var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
__p += 'never name your file like this.'; with(obj||{}){
return __p __p+='never name your file like this.';
}
return __p;
}; };

View File

@ -1,7 +0,0 @@
<div>
<div>
<div>
<%= obj.name %>
</div>
</div>
</div>

View File

@ -1 +1 @@
<head><title><%= obj.title %></title></head> <head><title><%= title %></title></head>

View File

@ -1 +0,0 @@
<head><title><%= title %></title></head>

View File

@ -6,7 +6,7 @@ exports['jst'] = {
var expect, result; var expect, result;
test.expect(10); test.expect(7);
expect = grunt.file.read("test/expected/jst.js"); expect = grunt.file.read("test/expected/jst.js");
result = grunt.file.read("tmp/jst.js"); result = grunt.file.read("tmp/jst.js");
@ -23,7 +23,7 @@ exports['jst'] = {
expect = grunt.file.read("test/expected/ns_nested.js"); // same as previous test expect = grunt.file.read("test/expected/ns_nested.js"); // same as previous test
result = grunt.file.read("tmp/ns_nested_this.js"); result = grunt.file.read("tmp/ns_nested_this.js");
test.equal(expect, result, "should define parts of nested namespaces, ignoring this."); test.equal(expect, result, "should define parts of nested namespaces, ignoring this.");
expect = grunt.file.read("test/expected/pretty.js"); expect = grunt.file.read("test/expected/pretty.js");
result = grunt.file.read("tmp/pretty.js"); result = grunt.file.read("tmp/pretty.js");
test.equal(expect, result, "should make the output be 1 line per template, making the output less ugly"); test.equal(expect, result, "should make the output be 1 line per template, making the output less ugly");
@ -32,21 +32,9 @@ exports['jst'] = {
result = grunt.file.read("tmp/amd_wrapper.js"); result = grunt.file.read("tmp/amd_wrapper.js");
test.equal(expect, result, "should wrap the template with define for AMD pattern"); test.equal(expect, result, "should wrap the template with define for AMD pattern");
expect = grunt.file.read("test/expected/amd_wrapper_no_ns.js");
result = grunt.file.read("tmp/amd_wrapper_no_ns.js");
test.equal(expect, result, "should wrap the template with define for AMD pattern and return the function itself with no namespace");
expect = grunt.file.read("test/expected/pretty_amd.js"); expect = grunt.file.read("test/expected/pretty_amd.js");
result = grunt.file.read("tmp/pretty_amd.js"); result = grunt.file.read("tmp/pretty_amd.js");
test.equal(expect, result, "should make the AMD wrapper output pretty"); test.equal(expect, result, "should make the AMD wrapper output pretty");
expect = grunt.file.read("test/expected/process_content.js");
result = grunt.file.read("tmp/process_content.js");
test.equal(expect, result, "should convert file content");
expect = grunt.file.read("test/expected/local_scope.js");
result = grunt.file.read("tmp/local_scope.js");
test.equal(expect, result, "should add `with` block when templateSettings.variable is undefined");
test.done(); test.done();
} }