Create pages with pre-compiling the templates

后端 未结 2 1492
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 08:29

In my current project, my work is only with html and css (HTML skinning). There are many pages which have repeated sections like Header, footer, sharing links etc.<

2条回答
  •  清歌不尽
    2020-12-22 09:09

    Explanation:

    Whenever I used to search on google for "pre-compiling templates", I was ending up on sites which were combining all the HTML template files to one single js file. But in my case, I was looking for a way to compile the templates completely on system itself with no support of a "all template compiled js file". (So, I was looking for a solution which pre-renders the HTMLs)

    Solution:

    I found this awesome template engine, Nunjucks, which lets me compile the HTML templates to Independent HTML pages when used with gulp.

    Check this one, gulp-nunjucks-render. By using this along with gulp, I am able to include section of .html files into other .html files. Here is the code (assuming you installed nodejs and gulp):

    var gulp = require('gulp');
    var nunjucksRender = require('gulp-nunjucks-render');
    
    gulp.task('default', function () {
        nunjucksRender.nunjucks.configure(['templates/'], { watch: false });
        return gulp.src('templates/!(_)*.html')
            .pipe(nunjucksRender({
                css_path: "../assets/css/",
                js_path: "../assets/js/",
                img_path: "../assets/images/"
            }))
            .pipe(gulp.dest('html'));
    });
    gulp.task('watch', function () {
        gulp.watch(['templates/*.html'], ['default']);
    });
    

    In the above code, I am keeping the HTML templates in templates folder and with the above gulp code, I am generating the new HTMLs in html folder. The above code will not generate the files which are prefixed with _. (something similar to sass)

    and later in command prompt:

    gulp watch  // Watches the files for changes continuously --> OWNING :D
    

    Here is an example:

    
    
    
        {% include "_head.html" %}
        
            {% include "_content.html" %}
            {% include "_footer.html" %}
        
    
    

    Which renders to:

    
    
        
            Website title
            
        
        
            

    Advantages:

    • No need of server support to compile the templates.
    • No need to include any pre-compiled js file in index.html.
    • Whenever we do some change in common section, no need to include that section again in every page.

    Disadvantages:

    • Till now, I didn't find any :).

提交回复
热议问题