0

I'm using dotless library for compile .less files in my asp.net web-site. And I want to get value of some variable by name.

For example, I have code like this:

@FONT_SIZE: 10px;
@TEXT_COLOR: red;

So, how can I get font size by "FONT_SIZE" name? I found FindVariable method in Env class, but I don't understand how to use it.

Sergey
  • 5,396
  • 3
  • 26
  • 38
  • Are you having problems precompiling the .less file or do you just want to know how to use .less variables? – Jun Wei Lee Dec 06 '13 at 14:21
  • I want to use following code: Env env = new Env(); string result = env.FindVariable("FONT_SIZE").Value.ToString(); – Sergey Dec 06 '13 at 15:35

3 Answers3

1

I have solved my issue using this code:

string GetLessVariableByName(string name, string lessContent) {
    int optimisation = 1;
    Func<IStylizer> defaultStylizer = () => new PlainStylizer();
    Func<IImporter> defaultImporter = () => new Importer();
    Func<Parser> defaultParser = () => new Parser(optimisation, defaultStylizer(), defaultImporter());
    Func<Env> defaultEnv = () => { return new Env(); };
    Env env = defaultEnv();
    Parser parser = defaultParser();
    var tree = parser.Parse(lessContent.Trim(), "tmp.less");
    var rule = tree.Rules.ToArray()[0];
    Node node = rule.Evaluate(env);
    var variableValue = tree.Variable(name, node);

    return variableValue == null ? null : variableValue.Value.ToString();
}
Zeeshan Ali
  • 347
  • 3
  • 12
Sergey
  • 5,396
  • 3
  • 26
  • 38
0

I wonder if your env will be static (needed to read your value). I think you should read your less file as text and use something like a regular expression to get your value. See: Import LESS from server howto read your less files. The same problem will be discussed here: https://groups.google.com/forum/#!topic/dotless/V3SROjkTpM8

Community
  • 1
  • 1
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224
0

Yes, I would use:

int optimisation = 1; Func<IStylizer> defaultStylizer = () => new PlainStylizer(); Func<IImporter> defaultImporter = () => new Importer(); Func<Parser> defaultParser = () => new Parser(optimisation, defaultStylizer(), defaultImporter()); Func<Env> defaultEnv = () => { return new Env(); }; Env env = defaultEnv(); Parser parser = defaultParser(); var tree = parser.Parse(lessContent.Trim(), "tmp.less"); var rule = tree.Rules.ToArray()[0]; Node node = rule.Evaluate(env);

Question though, where is the ToArray() coming from on the var rule = tree.Rules.ToArray()[0]; line?

Thanks, Jason

thejason
  • 51
  • 1
  • 6