使用gulp.js编译HTML片段

qij5mzcb  于 2022-12-08  发布在  Gulp
关注(0)|答案(5)|浏览(148)

有没有一个插件可用于Gulp,做同样的事情,因为组装做咕噜?
我想为Gulp运行一个组装HTML片段的任务,但是我找不到一个插件。有人用过吗?你能提供一个链接吗?

    • 更新日期:2016年4月21日**

最近,我一直在使用Twig.js和Gulp,以及gulp-data在我的模板中呈现JSON。我的文章将详细介绍。提示:你也可以使用双截棍,Swig.js,Handlebars等。

ifmq2ha2

ifmq2ha21#

Yes, you can do it with this plugin called gulp-file-include

  • Example :*
    # index.html
<!DOCTYPE html>
<html>
  <body>
  @@include('./view.html')
  @@include('./var.html', {
    "name": "haoxin",
    "age": 12345
  })
  </body>
</html>

# view.html

<h1>view</h1>

# var.html

<label>@@name</label>
<label>@@age</label>
pzfprimi

pzfprimi2#

我做了一个插件来扩展html文件https://www.npmjs.org/package/gulp-html-extend
master.html

<body>
    <!-- @@placeholder=content -->
    <!-- @@placeholder=footer -->
</body>

content.html

<!-- @@master=master.html-->

<!-- @@block=content-->
<main>
    my content
</main>
<!-- @@close-->

<!-- @@block=footer-->
<footer>
    my footer
</footer>
<!-- @@close-->

输出功率

<body>

<!-- start content -->
<main>
    my content
</main>
<!-- end content -->

<!-- start footer -->
<footer>
    my footer
</footer>
<!-- end footer -->

</body>

它可能会帮助你。

ppcbkaq5

ppcbkaq53#

我想再补充一点:
我使用gulp-preprocess。它不仅非常适合构建html,也非常适合构建JavaScript,甚至可以在PHP中使用。它有简单的指令:

<!-- @include filename.extension -->

    <!-- @ifdef foo -->
        Included html if foo is defined
    <!-- @endif -->

    Also @ifndef (not defined)

    Variables

    <!-- @echo bar -->

   Or even cooler:

    <a href="<-- @echo linkvar -->">link</a>

  Also (as far as I can tell) unlimited sub inclusion:

   <!--  I am an included file -->
   <!-- @include relative/to/me/data.html -->

我有一个这样的目录树:

./project root
         - build/
           - less/
             [less,..]
           - html/
               - index/
                 Index-variables.json
                 [Index-partials.html,...]
           Index.html
           [other-build-folders,..]

         - dist
           [htmlfiles,...,CSS folder,...]

对于每个呈现的html文件,我在build文件夹中都有一个对应的文件,并且该文件名也有一个对应的文件夹。* build file * 监听对应文件夹中的更改,并对数据进行预处理,然后输出到 * dist * 文件夹中的匹配文件。
由于预处理允许将变量作为上下文对象传递,因此我传递了存储在父build文件夹的JSON文件中的变量,例如index-variables.json,覆盖了我定义的任何全局变量。
我在Liverload中使用了它,所以结果是每次我对任何html片段进行修改时,页面几乎会立即重新加载渲染的html--我们说的是不到1秒。除了 lightning 般的速度之外,预处理似乎真的很稳定--我从来没有遇到过bug。
这是一个很棒的工作方式。

zmeyuzjn

zmeyuzjn4#

Assemble现在支持Gulp:https://github.com/assemble/assemble虽然在发布的时候官方汇编网站没有提到这一点,而且文档的方式也很少。

o4tp2gmn

o4tp2gmn5#

你可以用一个叫gulp-handlebars-file-include的gulp插件来实现
这是一个非常好的插件,因为它没有创建或定制一个自定义的解析器,比如gulp-file-include,也没有定义一个新的语法。相反,它使用handlebars,因此,它不仅用handlebars进行解析,而且你还可以用handlebars编译你的部分文件,甚至包括你自己的handlebars助手。

相关问题