Nunjucks 渲染文件路径相对于被调用的路由并覆盖 express.static 设置

Nunjucks rendering file paths relative to route being called and overriding express.static setting

将 Nunjucks 与节点一起使用

正在尝试找出以下问题的完美解决方案。使用这样的目录树 sorda: app_dir --app.js --public ----stylesheets ------mystyles.css --views ----page.html ----templates ------page_template.html

  1. 我的 public 目录中有像 CSS 这样的静态文件 app.use(express.static(path.join(__dirname, 'public')));
  2. 将Nunjucks的根目录配置为views nunjucks.configure('views', { autoescape: true, express : app, watch: true });

  3. 当我从 page_template.html 中引用 css 文件时,nunjucks(我认为)会根据路由自动创建一个相对路径并覆盖静态行为。

例如,当我在 page_template.html 上使用 /stylesheets/mystyles.css 路径但调用扩展它的文件时 /:publication/:page路径,渲染后的html是/:publication/:page/stylesheets/mystyle.css

我总是可以编写一个快速的 hack,根据路由创建到 CSS 和其他资源的相对路径,但这并不是一个特别优雅的解决方案:(非常感谢任何帮助。

When I am referencing a css file from within page_template.html, nunjucks (I think) automagically creates a relative path based on the route and overrides the static behavior.

我认为这是错误的。 Nunjucks 不生成任何路径。
在来自任何文件夹(viewview/templates 等)的模板中,考虑到 public dir 是根目录,您必须指定文件名,例如 /stylesheets/mystyles.css 对于 %app%/public/stylesheets/mystyles.css.

我使用 view 中的子文件夹对模板进行分组,例如/macros(存储的宏),/tools(为我的应用存储额外的页面)。你也可以用它来路由器,例如/user/view.htmluser/add.html...