Link to static files from Jade template rendered from a sub route

南笙酒味 提交于 2020-01-11 10:54:25

问题


I have a very basic problem with Node.js/Express/Jade that's surprisingly hard to describe. In my node.js application I use the Express framework for routing of HTTP requests. I also use Jade templates as views, who themselves link to files (css, js etc.) inside a directory that I have declared as static through the app.use(express.static(__dirname + '/public')); command.

When I route requests to resources like /about or /contact everything works as expected. But I found that as soon as my resources have multiple 'levels' like so /about/me the same jade view would still render, but it ends up in the browser without CSS styling!

So my assumption is that the virtual directories represented by the resource levels screw up where jade thinks it must look for relative paths (in this case, where to find the public directory containing the static files).

I can't just prefix the paths inside the jade template since I have to use the same template for different resource types, so I need a solution that works for arbitrary resource levels.

Is there such a solution?


回答1:


I am guessing that your Jade template has something that looks like the following:

doctype html
  head
    link(rel="stylesheet", type="text/css", href="css/style.css")
    ...

The href for the stylesheet is a relative path, meaning your browser will look for the CSS file relative to the page it is currently on. For example:

  • http://example.com/abouthttp://example.com/css/style.css
  • http://example.com/about/companyhttp://example.com/about/css/style.css

You can change the href to an absolute path so the CSS file location will always be constant no matter what sub-directory you are in:

link(rel="stylesheet", type="text/css", href="/css/style.css")

The key change here is the forward slash at the beginning of the href, turning the relative path into an absolute one.



来源:https://stackoverflow.com/questions/23447449/link-to-static-files-from-jade-template-rendered-from-a-sub-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!