|
| 1 | +# Add AngularJS templates to cache and inline it on page |
| 2 | + |
| 3 | +This recipe assumes that your templates are in `src/templates`. It does a two-step substitution in order to achieve its goal, because it needs the Javascript and HTML to be minified with existing configurations, and then it inlines the generated template cache code. It also assumes that you have a module called `MY_MODULE_NAME`. |
| 4 | + |
| 5 | + |
| 6 | +1. Install packages [gulp-substituter](https://www.npmjs.org/package/gulp-substituter) and [gulp-angular-templatecache](https://www.npmjs.org/package/gulp-angular-templatecache) package <br> |
| 7 | + ``` |
| 8 | + npm install gulp-substituter --save-dev |
| 9 | + npm install gulp-angular-templatecache --save-dev |
| 10 | + ``` |
| 11 | + |
| 12 | +2. Add this code to your Gulpfile: |
| 13 | + |
| 14 | +```javascript |
| 15 | +var fs = require('fs'); |
| 16 | +var substituter = require('gulp-substituter'); |
| 17 | +var templateCache = require('gulp-angular-templatecache'); |
| 18 | + |
| 19 | +gulp.task('templates', ['index'], function(cb) { |
| 20 | + gulp.src('./dist/templates/**/*.html') |
| 21 | + .pipe(templateCache('templates.js', { |
| 22 | + root: '/templates', |
| 23 | + module: 'MY_MODULE_NAME' |
| 24 | + })) |
| 25 | + .pipe(gulp.dest('dist/scripts')) |
| 26 | + .on('end', function() { |
| 27 | + gulp.src('./dist/index.html') |
| 28 | + .pipe(substituter({ |
| 29 | + templates: function() { |
| 30 | + var templates = fs.readFileSync('dist/scripts/templates.js').toString() |
| 31 | + .replace(/<\/script>/g, '</scr" + "ipt>') |
| 32 | + .replace(/\n/g, ''); |
| 33 | + return '<script type="text/javascript">' + templates + '</script>'; |
| 34 | + }, |
| 35 | + __start: '<', |
| 36 | + __end: '/>', |
| 37 | + __prefix: 'replace' |
| 38 | + })) |
| 39 | + .pipe(gulp.dest('dist')) |
| 40 | + .on('end', cb); |
| 41 | + }); |
| 42 | +}); |
| 43 | +``` |
| 44 | + |
| 45 | +3. Optionally, add the following to your Pho configuration <br> |
| 46 | + `defaultDependencies: ['templates']` |
| 47 | + |
| 48 | +4. Add the following to your page, after loading AngularJS and your controllers <br> |
| 49 | + `<!-- substitute:templates -->` |
| 50 | + |
| 51 | +5. Run the new task <br> |
| 52 | + `gulp templates` |
0 commit comments