Skip to content
Mária Jurčovičová edited this page Sep 17, 2015 · 7 revisions

Less4j makes it possible to configure additional variables from java. Additional variables are added into global scope e.g. they behave as if they would be written at the end of compiled sheet.

If you want to add variables one by one, use the addExternalVariable(String name, String value) method of the configuration object. If you want to add variables in bulk, use the addExternalVariables(Map<String, String> variables) method. Keys in the map are used as additional variable names and values as variable values.

Example 1 - add variables one by one

// define less sheet
StringSource less = new StringSource("" +
    "div {                            " +
    "    @variable-detached();        " +
    "    color: @variable-color;      " +
    "}                                " +
    "@variable-color: overriden;      " +
    "");
    
// configure additional variables
Configuration configuration = new Configuration();
configuration.addExternalVariable("@variable-detached", "{ detached: ruleset; }");
configuration.addExternalVariable("@variable-color", "green");

// compile
LessCompiler compiler = new DefaultLessCompiler();
CompilationResult compilationResult = compiler.compile(less, configuration);

//print compiled css
System.out.println(compilationResult.getCss());

prints:

div {
  detached: ruleset;
  color: green;
}

Example 2 - add variables in bulk

// define less sheet
StringSource less = new StringSource("" +
    "div {                            " +
    "    @variable-detached();        " +
    "    color: @variable-color;      " +
    "}                                " +
    "@variable-color: overriden;      " +
    "");
    
// define additional variables
Map<String, String> variables = new HashMap<String, String>();
variables.put("@variable-detached", "{ detached: ruleset; }");
variables.put("@variable-color", "green");

// configure additional variables
Configuration configuration = new Configuration();
configuration.addExternalVariables(variables);

//print compiled css
System.out.println(compilationResult.getCss());

prints:

div {
  detached: ruleset;
  color: green;
}