Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layout inheritance in jade

Tags:

node.js

pug

If you don't know what jade is.
I am having problem with the template inheritance system.My file structure is like so

/views/
   |-- layout.jade
   /products/
      |-- index.jade
      |-- product.jade
/static/
   /stylesheets/
      |-- style.css

The problems is that when loading the product page which receives an id as param (localhost:3000/product/:id if not for the /id it would load just fine), although the layout still extends correctly it does not load the stylesheet properly (the path is broken). I am doing half of it right though, in the index page of products the stylesheet loads just fine.

Layout.jade

  head
    link(rel='stylesheet', href='stylesheets/style.css')
like image 249
andrei Avatar asked Nov 24 '11 23:11

andrei


1 Answers

It's probably the relative path in your href. Digging around the express documentation, I'm finding that the most popular approach is to reference the stylesheet from the base of the site like this (notice the / preceding stylesheets):

link(rel='stylesheet','/stylesheets/style.css')

This has the benefit of being easy, and working across routes of multiple depths (/about, /about/me, etc). However, it has the negative of not supporting app directory depth. For example, if you wanted to host your app at: http://yourserver/yourapps/yourapp this would be a problem. I don't know if you care about this or not, most of the examples for express certainly don't :-)

However, if you want to do this the right way, there is one example on the express github site: blog. https://github.com/visionmedia/express/tree/master/examples/blog

The approach here is to use a middleware component to grab the base url, and stuff it in the locals passed down to the layout view. Here's what your HTML would look like:

!!! 5
html
  head
    title Blog
    link(rel='stylesheet', href=base + '/style.css')
  body
    #container!= body

The important parts to check out if you require this approach are middleware/locals.js, app.js where the middleware component is wired up, and layout.jade where the base href is used.

Happy Coding!

like image 145
Justin Beckwith Avatar answered Nov 12 '22 03:11

Justin Beckwith