Node app variables passed into stylus file
Asked Answered
O

2

5

I am building a little node app and using Express with Jade and Stylus to render some basic HTMl pages.

I was curious if there is a way for me to pass some variables INTO the .styl file that are generated from Node? I am well aware that i can define variables inside of the .styl file but I have a need to be more dynamic. Specifically i was looking for an easy way to store some colors in the db, have node grab those values, then insert those into the .styl file so that when the page is rendered these variables are passed in. It seems like this should be do-able but i am lacking on the details. Any help is appreciated. Thanks!

Opprobrium answered 24/9, 2012 at 22:38 Comment(0)
H
6

You can use the Stylus API's define() function to set Stylus variables and make JS functions available to it.

Homburg answered 25/9, 2012 at 1:15 Comment(0)
O
6

Thanks to @ebohlman as his advice was close to what i ultimately implemented.

basically i was trying to figure out how to do this on top of the Connect Middleware and here is what i came up with:

when doing app.configure i used the custom compile compile function (key 'compile') like so:

app.use(require('stylus')
  .middleware({
    src: app.root + '/app/public',
    compile: compile
  })
);

then i created a couple of functions:

var stylus = require('stylus');
var mylib = function(style){
  style.define('themeColor1', function(){
    //call to the db that returns a color
    color = 'blue';
    color = color ? color : 'orange';
    return new stylus.nodes.Literal(color);
  });
};

var compile = function(str, path) {    
  return stylus(str)
    .use(mylib);
};

then inside of the .styl file i do:

background-color themeColor1();

the ternary operator in the themeColor1 function allows for easy defaults and an override. It took me a bit to figure out the API based upon the examples but it seems like this COULD be a solution others would want to know how to do. If anyone has any downfalls of this approach please let me know.

Opprobrium answered 25/9, 2012 at 17:38 Comment(2)
Do you know how to just pass a variable from node to stylus without creating a function. I saw the answer here for .define() but it doenst seem to work for me.Fotheringhay
I found that Literal doesn't work as expected, I had to use IdentForklift

© 2022 - 2024 — McMap. All rights reserved.