Search code examples
node.jstemplatesgulpassemble

How to include corresponding css and javascript of the page in assemble layout


I am using assemble to generate from html files with a common layout files. I want to include the corresponding css and javascript file with different pages. So that, for index.html, only index.css and index.js are included, and for about-us.html, only about-us.css and about-us.js are included.

Here's my respository on github https://github.com/xchitox/assemble-gulp-test


Solution

  • If you are already using gulp then use gulp-inject to inject the html files with their respective dependencies based on injection tags.

    function injectStartingTag(filepath, starttag) {
    
        var inject = require('gulp-inject');
    
        // Injects the source using relative paths
        return inject(gulp.src(filepath, {
            read: false
        }), {
            relative: true,
            starttag: '<!-- ' + starttag + ' -->'
        });
    }
    

    In your index.html:

    <!--inject:index:css-->
    <!--endinject-->
    
    <!--inject:index:js-->
    <!--endinject-->
    

    In your about-us.html:

    <!--inject:about-us:css-->
    <!--endinject-->
    
    <!--inject:about-us:js-->
    <!--endinject-->
    

    Call the function above in any gulp task. You can filter with gulp-if and call the function with the specific starttag. i.e.:

    gulp.task('Inject', function(){
    
        var _if = require('gulp-if');
    
        var all_your_files = "**/*.*"; // obvously only add html, js, and css files
    
        return gulp
            .src(all_your_files)
            .pipe(_if('index.html', injectStartingTag('index.css', 'inject:index:css')))
            .pipe(_if('about-us.html', injectStartingTag('about-us.css', 'inject:about-us:css')))
            ...
            ...
            // you get the idea
    });