Dynamically set LESS variables from user settings

2019-07-17 15:04发布

This is a simple matter to explain really. It's either possible or it's not.

I have user settings in the DB, or will have at least. These settings will contain things like font sizes, colors and opacity. I need to get them from the member object and into the LESS styles.

Before I go on I should let you know that I'm using Node.js + Sails.js + MongoDB.

My member object will look similar to ( truncated data ):

{ 
    _id: ObjectId("52afc219c41e159808d41be5"),
    createdAt: ISODate("2013-12-17T03:16:41.947Z"),
    email: "someemail@provider.com",
    encryptedPassword: "$2a$10$TJ2vMgRpG1y/pYrHPWyDp.pd9u9lgHqNTOSV5fob2yckIFdQsxQea",
    firstName: "Firstname",
    lastName: "Lastname",
    updatedAt: ISODate("2013-12-27T22:40:34.057Z"),
    textSize: 14,
    textColor: "#333333",
    widgetOpacity: 0.7
}

In the LESS file I need to be able to set the @vars at the top with this data:

@textSize: member.textSize;
@textColor: member.textColor;
@widgetOpacity: member.widgetOpacity;

Or

@textSize: <%- member.textSize %>;
@textColor: <%- member.textColor %>;
@widgetOpacity: <%- member.widgetOpacity %>;

Of course all of this throws errors. Please point out what I'm failing to do here. Thanks.

1条回答
孤傲高冷的网名
2楼-- · 2019-07-17 15:29

I think this depend on when you read the user object and write your less files. If you compile your LESS files client side, see http://lesscss.org/#usage you will have option to manipulate vars on real time, see: Changing variable dynamically (at runtime) via LESS and CSS?.

In most cases you pre-compile you LESS to CSS and load the CSS in your browser. I think you have 2 option in this case:

  1. compile your css, based on user setting, before you write the page, example http://twitterbootstrap3buttons.w3masters.nl/
  2. use javascript / jquery to manipulate your css after compiled and laod, see: Modifying CSS on the fly using jquery
查看更多
登录 后发表回答