|
| 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 steps 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 generate 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('gzip', function(cb) { |
| 20 | + gulp.src('./dist/**') |
| 21 | + .pipe(gzip({ |
| 22 | + append: true, |
| 23 | + level: 9 |
| 24 | + })) |
| 25 | + .pipe(gulp.dest('dist')) |
| 26 | + .on('end', cb); |
| 27 | + }); |
| 28 | + |
| 29 | +gulp.task('templates', ['index'], function(cb) { |
| 30 | + gulp.src('./dist/templates/**/*.html') |
| 31 | + .pipe(templateCache('templates.js', { |
| 32 | + root: '/templates', |
| 33 | + module: 'MY_MODULE_NAME' |
| 34 | + })) |
| 35 | + .pipe(gulp.dest('dist/scripts')) |
| 36 | + .on('end', function() { |
| 37 | + gulp.src('./dist/index.html') |
| 38 | + .pipe(substituter({ |
| 39 | + templates: function() { |
| 40 | + var templates = fs.readFileSync('dist/scripts/templates.js').toString() |
| 41 | + .replace(/<\/script>/g, '</scr" + "ipt>') |
| 42 | + .replace(/\n/g, ''); |
| 43 | + return '<script type="text/javascript">' + templates + '</script>'; |
| 44 | + }, |
| 45 | + __start: '<', |
| 46 | + __end: '/>', |
| 47 | + __prefix: 'replace' |
| 48 | + })) |
| 49 | + .pipe(gulp.dest('dist')) |
| 50 | + .on('end', cb); |
| 51 | + }); |
| 52 | +}); |
| 53 | +``` |
| 54 | + |
| 55 | +3. Add the following to your Pho configuration <br> |
| 56 | + `defaultDependencies: ['templates']` |
| 57 | + |
| 58 | +4. Add the following to your page, after loading AngularJS and your controllers <br> |
| 59 | + `<!-- substitute:templates -->` |
| 60 | + |
| 61 | +5. Run the task compilation <br> |
| 62 | + `gulp templates` |
0 commit comments