【问题标题】:How to include corresponding css and javascript of the page in assemble layout如何在组装布局中包含页面的相应css和javascript
【发布时间】:2016-05-31 14:09:47
【问题描述】:

我正在使用 assemble 从具有通用布局文件的 html 文件生成。我想在不同的页面中包含相应的 css 和 javascript 文件。这样,index.html 只包含 index.css 和 index.js,而 about-us.html 只包含 about-us.css 和 about-us.js。

这是我在 github 上的存储库https://github.com/xchitox/assemble-gulp-test

【问题讨论】:

    标签: node.js templates gulp assemble


    【解决方案1】:

    如果您已经在使用 gulp,则使用 gulp-inject 根据注入标签注入具有各自依赖项的 html 文件。

    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 + ' -->'
        });
    }
    

    在你的 index.html 中:

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

    在您的 about-us.html 中:

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

    在任何 gulp 任务中调用上述函数。您可以使用gulp-if 进行过滤,并使用特定的起始标签调用该函数。即:

    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
    });
    

    【讨论】:

    • 感谢@Wilmer Saint。 gulp-inject 满足我的要求。但是我使用 gulp-flatMap 而不是 gulp-if 将相关的 js 和 css 文件注入到不同的 html 文件中。
    【解决方案2】:

    您可以使用帮助程序根据当前视图的文件名生成指向资产的链接:

    app.helper('filename', function() {
      // this.view is the current view being rendered
      return this.view.stem; // just get the basename without extension
    });
    

    现在您可以使用它在布局中添加资产路径:

    <link rel="stylesheet" href="/assets/css/{{filename}}.css">
    <script src="/assets/js/{{filename}}.js"></script>
    

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 2010-10-03
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多