Jade conditionally based on the page url?

Is it possible to set a jade condition in my layout template based on the page path? Is there a page path variable? I'm looking to do things like:

if page = "/about"
  link(rel='stylesheet', href='css/about')
else
  link(rel='stylesheet', href='css/main')

      

If it's part of a layout template. Where and how to define the variables for this?

+3


source to share


3 answers


Yes, it is possible:

- var page = window.location.pathname

if page === "/about"
   link(rel='stylesheet', href='css/about.css')
else
   link(rel='stylesheet', href='css/main.css')

      



Note that the above snippet assumes that the template is executed in a browser environment. If it is not, you can get the path name using the language you are using and pass it to the template as a database. For example, if you are using the Express framework, the path

object property request

returns the path to the URL.

+4


source


Depends on your setup

Express:

res.locals.cssPath = 'css/about.css';
res.render('about');

      



Jade: Not sure about the syntax here since I am not using jade, but you have access to locals

link(rel='stylesheet', href=cssPath)

      

0


source


I would set the path dynamically using req.path in express:

res.locals.path = req.path;
res.render('about');

      

and then using the path in the Jade file:

if path === "/about/"
   link(rel='stylesheet', href='css/about.css')
else
   link(rel='stylesheet', href='css/main.css')

      

0


source







All Articles