有没有办法在链接中使用动态相对路径,而不是在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树中的位置,我可以在Jade模板中使用某种get relative path函数吗?
发布于 2014-01-18 17:21:01
我使用特殊的post-processing构建步骤,遍历所有生成的HTML文件,然后将其中包含的链接转换为它们的相对变体。
此方法适用于任何模板语言(例如,nunjucks),因为它不修改模板,而是修改最终的可交付成果。
它不能与wintersmith的实时预览服务器一起工作。
我使用Cheerio超文本标记语言解析器。
核心功能是这样的:
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;
}发布于 2013-09-23 03:13:43
我一直在使用的一种解决方案是使用不同的配置进行构建:
因此,不要使用默认的"config.json",这将使您的构建设置变得混乱,例如:"config.build.json“设置您的urls如何设置它们,当您完成设置时,只需运行:
wintersmith build -c config.build.json(同样,这可能是众多解决方案中的一个,我也在不断地寻找更好的解决方案进行部署)
https://stackoverflow.com/questions/15450574
复制相似问题