Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing dynamic CSS with Jade

Tags:

css

node.js

pug

I'm trying to write out some dynamic CSS using Jade, like so:

style(type='text/css')
    each item in colors
        .#{item.class} { background-color : #{item.background}; color: #{item.foreground}; }

However this gives the following error:

ReferenceError: media='print')
    7|  style(type='text/css')
  > 8|      - for(var item in colors)
    9|          .#{item.class} { background-color : #{item.background}; color: #{item.foreground}; }
    10| block Content
    11|     include scheduleTemplate

item is not defined

If I remove the style tag, it renders fine. Is there any way to use iteration within a style block?

like image 369
Tyler Schroeder Avatar asked Mar 30 '12 16:03

Tyler Schroeder


3 Answers

Another way is to import your own css stylesheet. In the Jade doc, you can see that you can include a style sheet with such code:

html
  head
    style
      include style.css

Then, you can define any CSS in a separate file that you can reference.

like image 168
Vince Avatar answered Nov 10 '22 10:11

Vince


Because style tags only allow text in Jade, it's treating your each item in colors as plain text. Then it encounters the #{item.class} and attempts to parse that, but it fails because it didn't define item on the previous line.

Unfortunately, I'm not sure that there is a good way to do this in Jade. You might just have to define all of your css ahead of time in JS and then insert it like so:

style(type='text/css')
    #{predefined_css}

At that point though, it might be simpler to just move the styles to an external stylesheet that gets generated for each user and then serve it with some reasonable caching headers. That would avoid the difficulties with trying to make Jade do dynamic CSS and speed up subsequent page loads for your users.

like image 10
Nathan Friedly Avatar answered Nov 10 '22 09:11

Nathan Friedly


You could use Stylus. It's made by the same people that created Jade and is almost identical to Jade within reason.

like image 3
Daniel Avatar answered Nov 10 '22 08:11

Daniel