使用gulp-file-include从HTML模板到文件的相对路径

Relative path to a file from an HTML template using gulp-file-include

本文关键字:文件 相对 路径 gulp-file-include HTML 使用      更新时间:2023-09-26

使用gulp-file-include从HTML模板中链接到CSS和JavaScript文件的推荐方法是什么?

的例子:

index . html

@@include('templates/doc-begin.html')
<h1>Welcome</h1>
<p>Hello!</p>
@@include('templates/doc-end.html')

支持/index . html

@@include('templates/doc-begin.html')
<h1>Support</h1>
<p>RTFM</p>
@@include('templates/doc-end.html')

模板/doc-begin.html

<!doctype html>
<html lang=en>
<head>
   <title>Website</title>
   <link rel=stylesheet href=?????/style.css>
</head>
<body>

两个index.html文件位于不同的文件夹级别,因此link标记中样式表的相对路径不能硬编码(绝对路径有自己的问题,在这种情况下是不可取的)。

基本上第一个link标签需要是这样的:
<link rel=stylesheet href=style.css>

,第二个类似于:

<link rel=stylesheet href=../style.css>

是否有一个方便的方法在gulp-file-include做到这一点?

注意:
我目前有一个解决方案,我将一个变量作为".", "..""../.."传递到每个@@include调用中,但这很麻烦且脆弱。

由于没有答案发布,以下是我的变通办法:

index . html

@@include('templates/doc-begin.html', { "webRoot": "." })
<h1>Welcome</h1>
<p>Hello!</p>
@@include('templates/doc-end.html', { "webRoot": "." })

支持/index . html

@@include('templates/doc-begin.html', { "webRoot": ".." })
<h1>Support</h1>
<p>RTFM</p>
@@include('templates/doc-end.html', { "webRoot": ".." })

模板/doc-begin.html

<!doctype html>
<html lang=en>
<head>
   <title>Website</title>
   <link rel=stylesheet href=@@webRoot/style.css>
</head>
<body>


更新(2017年4月):
webRoot特性已添加到gulp-file-include
https://github.com/coderhaoxin/gulp-file-include webroot-built-in-context-variable