4

I'm trying to get my Jade template to write a hyperlink (<a>) relative to the current URL.

For example, my view is called from http://localhost/cats and it looks like this:

extends layout

block content
  a(href='fluffy') Fluffy

When the link is clicked, it takes me to http://localhost/fluffy, instead of http://localhost/cats/fluffy

Things I've tried:

  • a(href='./fluffly')
  • a(href='\\fluffy')
  • a(href='/fluffy')

Just about the only thing that works is writing out the absolute path, like a(href='cats/fluffy'). Surely there's a better way to do it.

4

2 回答 2

3

正如您自己已经注意到的那样,当您打开/cats时,可以预期一个相对链接fluffy会引导您进入/fluffy:)

一点背景:Express 的默认行为是将/cats/cats/视为相同,并且两者都会触发相同的路由。

您要么在创建链接(尤其是相对链接)时考虑到这一点,要么告诉 Express 将它们视为两条独立的路线:

app.enable('strict routing');

app.get('/cats/', function(req, res) {
  ...
});

这将匹配/cats/,但不是/cats。当然,当您在路由定义中去掉尾部斜杠时,这种行为将被逆转。

于 2013-07-12T20:04:54.017 回答
2

如果您正在使用gulp-jade,请添加gulp-data到组合中并使用以下代码:

var jade = require('gulp-jade');
var data = require('gulp-data');

gulp.src('**/*.jade')
  .pipe(data(function (file) {
    var relativePath = file.history[0].replace(file.base, ''); //e.g. about/index.jade
    var depth = (relativePath.match(/\//g) || []).length; //e.g. 1
    var relativeRoot = new Array(depth + 1).join( '../' ); //e.g. ../
    return {
      relativeRoot: relativeRoot
    };
  }))
  .pipe(jade())

这将relativeRoot在您的jade模板中为您提供一个本质上是:<nothing>../重复的次数与其相对于基本文件夹嵌套的目录数量一样多。

然后,在您的模板中:

link(rel='stylesheet', href= relativeRoot + 'assets/main.css')

我不完全确定file.history生成的位置/方式,但在我的情况下[0]指向原始文件名(其磁盘上的绝对路径)

于 2014-11-12T16:37:13.880 回答