sintaxi / harp

Static Web Server/Generator/Bundler
http://harpjs.com
5k stars 342 forks source link

Page Specific Stylesheets #566

Closed jbaldo closed 4 years ago

jbaldo commented 8 years ago

Question about the best way to achieve page specific styling in Harp.

One approach is documented here. Essentially, define custom stylesheets in _data.json for each page and iterate over each collection and include on the page. That should work, but for performance reasons, it's a shame to have to make so many http requests.

I'm wondering if there's a better way. It would be great to dynamically include partials in a main.scss based on current.source like you would in a jade or ejs template. But I'm guessing scss is only processed once, not for each page? And current.source isn't exposed in a scss file.

So the only other method I can think of to get everything into one would request would be something like:

├── index.ejs
├── style
│   ├── index.scss
│   └── _main.scss

index.scss

@import 'main';
// some page specific scss

index.ejs

<link rel="stylesheet" href="style/<%- current.source %>.css">

Are there any other common patterns for this? Thanks for any thoughts. Sorry if this is a dupe question. Didn't find much on a search.

matteo-bombelli commented 8 years ago

If you would like to have different things on the same file you can just add a class to the body like

<body class="page-<%- current.source %>">

so you can use the file name as a class for filtering the css... or a more complex approach similar to the one wordpress has

https://developer.wordpress.org/reference/functions/body_class/

I'm implementing this functionality into my project:

https://github.com/matteo-bombelli/harp-ejs-functions/blob/master/moduleSet/common/functions/lib/frameworks.ejs#L96

this function is part of a big modular way of using harp...


if you prefer you can use

├── index.ejs
├── post.md
├── blog
│   └── post.md
├── style
│   ├── blog
│   │   └── post.scss
│   ├── index.scss
│   ├── post.scss
│   └── _main.scss

and use

<% var cssurl=current.path.join("/") %>
<link rel="stylesheet" href="/style/<%- cssurl %>.css">

in this way you can have different styles for /post and /blog/post

in harp there are no standard rules: you can do what you prefer...

Personally i would prefer to do something different: specify the path in the data.json file

{
  "index":{
     "cCssFile":"style/index.css"
  }
}

and in the header/layout:

<% if(typeof cCssFile !== "undefined" ){ if(cCssFile){%>
<link rel="stylesheet" href="<%- cCssFile %>">
<& } } %>

so you're not forced to have a css for every page...