替换wintersmith玉模板中的根相对路径

时间:2013-03-16 14:40:14

标签: pug

有什么方法可以在链接中使用动态相对路径而不是wintersmith模板中的根相对路径?

我不能使用src="/scripts/main.js"之类的根实体链接,因为预览构建服务器将网站嵌入任意深的子文件夹中,例如:

/stage/workspace/build/scripts/main.js
/stage/workspace/build/index.html
/stage/workspace/build/about/index.html

在生产服务器上,所有内容都在根URL下,因此根相对链接在那里工作正常,但我也希望在我们的暂存预览服务器上可以查看这些构建。如何在我的jade模板上设置链接,以便它始终使用相对链接,例如来自about us页面的脚本链接:../scripts/main.js,而主页为scripts/main.js 。我想让两个页面都使用相同的玉石模板,模板会找出每个页面的相对链接。

我是否可以在Jade模板中根据wintersmith中树的内容位置使用某种获取相对路径函数?

2 个答案:

答案 0 :(得分:1)

我使用了特殊的后期处理构建步骤,该步骤遍历所有生成的HTML 文件,并将将链接转换为其相对变体。< / p>

此方法适用于任何模板语言(例如nunjucks),因为它不会修改模板,但会修改最终的可交付成果。

它不适用于wintersmith的实时预览服务器。

我使用Cheerio HTML解析器。

核心功能如下:

var cheerio = require("cheerio");
var fs = require("fs");
$ = cheerio.load(fs.readFileSync(expandFileName("build/test.html"), 'utf-8'));

// change all links in the cheerio document from absolute to relative.
// document's absolute location is supposed to be /test/test.html
rebaseDocument("/test/test.html", $);

fs.writeFileSync(expandFileName("build/test.new.html"), $.html());
return;

function rebaseDocument(documentLocation, $) {
  debugLog(documentLocation);
  rebaseElements(documentLocation, $, "a", "href");
  rebaseElements(documentLocation, $, "link", "href");
  rebaseElements(documentLocation, $, "script", "src");
  rebaseElements(documentLocation, $, "img", "src");
}

function rebaseElements(documentLocation, $, tagName, attributeName) {
  $(tagName).each(function() { $(this).attr(attributeName, rebaseLink(documentLocation, $(this).attr(attributeName))); });
}

function rebaseLink(documentLocation, link) {
  if (link == null)
    return link;

  // check if link denotes absolute hyperlink. If so, nothing to do here
  // absolute hyperlink is either scheme:// or protocol relative url //
  if ((new RegExp('^([a-z]+://|//)')).test(link))
    return link;

  // check another special forms of absolute hyperlinks
  if (link.substring(0, 7) == "mailto:")
    return link;

  // if link is already relative, nothing to do
  if (link.charAt(0) != '/')
    return link;

  if (documentLocation.charAt(0) != '/')
    documentLocation = '/' + documentLocation;

  var path = require("path");
  var documentName = path.basename(documentLocation);
  var from = path.dirname(documentLocation);
  var newLink = path.relative(from, link).replaceAll("\\", "/");

  // reduce 'document.htm#anchor' to '#anchor'
  if (newLink.slice(0, documentName.length + 1) == documentName + '#')
    newLink = newLink.slice(documentName.length);

  return newLink;
}

答案 1 :(得分:0)

我一直在使用的一个解决方案是使用不同的配置进行构建:

所以不要使用默认的“config.json”,否则会破坏你的构建 设置专门用于构建的配置,例如:“config.build.json” 设置你的网址你想要如何设置它们,当你完成后, 刚跑:

wintersmith build -c config.build.json

(同样,这可能是众多解决方案中的一种,我也在不断寻找更好的部署解决方案)