Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Get variables from .LESS markup

I'm using ASP.NET MVC 5 and would like to create a page that lists a .less file's variables and their values as textboxes. My goal is to make a small page that lets you edit their values.

 public JsonResult GetLessVariables()
    {
        var file = System.IO.File.ReadAllText("~/some.less");

        /*  
            Create key value pair of variable and value from file
                i.e
                   @body-color, #000000
                   @text-color, #ffffff
        */

        return Json(data, JsonRequestBehavior.AllowGet);
    }

Is there some easy way to get them into a key value pair dictionary or similar?

EDIT: Example of .less file:

//
// Test
// --------------------------------------------------

    @body-color:     #000000;
    @text-color:     #ffffff;


    // Test
    .test {
        background: @body-color;
        color: @text-color;
    }
    ....  and so on

Upvotes: 1

Views: 460

Answers (1)

Paul Turner
Paul Turner

Reputation: 39625

If the file only contains variable definitions, you could match the variables with a quick-and-dirty regular-expression:

var regex = new Regex(@"(?<name>@\w+)\s*:\s(?<value>[^;]+;");

var less = File.ReadAllText("style.less"));

var matches = regex.Matches(less);
var parameters = new List<KeyValuePair<string, string>>();
foreach (var match in matches.Cast<Match>())
{
    parameters.Add(new KeyValuePair<string, string>(
        match.Groups["name"].Value,
        match.Groups["value"].Value));
}

Untested, may require tweaking, but should suffice if you can keep the markup simple. If you add a constraint to match whole lines, you can probably get away with running it on your sample, but you risk capturing variables nested at different scopes - a regex is not a good tool for complex syntax.

If you can't move the variables to their own file or add constraints, you'll have employ a much more complex grammar parser to extract the variable declaration statements.

It may be that the DotLess project has a parser you can make work for you.

Upvotes: 1

Related Questions