Skip to content

Extending Less Language

Mária Jurčovičová edited this page Mar 20, 2014 · 68 revisions

Warning: this feature is still in experimental mode.

If less4j does not contain all functions you need, extend it with custom functions.

Overview

Custom function must implement LessFunction interface. It has two methods:

public interface LessFunction {
  public boolean canEvaluate(FunctionExpression input, List<Expression> parameters);
  public Expression evaluate(FunctionExpression input, List<Expression> parameters, Expression evaluatedParameter, LessProblems problems);
}

The canEvaluate method analysis input function and returns true only if the custom function can evaluate the input. Second evaluate method is called only if the canEvaluate returned true.

Custom functions are passed to less4j using addCustomFunction and addCustomFunctions methods of the Configuration object

Configuration configuration = new Configuration();
configuration.addCustomFunction(new CustomFunction());
CompilationResult compilationResult = compiler.compile(inputLessFile, configuration);

Example

Following custom function evaluates only constant() function calls and always returns the same result:

class ConstantFunction implements LessFunction {

  @Override
  public boolean canEvaluate(FunctionExpression input, List<Expression> parameters) {
    return input.getName().equals("constant");
  }

  @Override
  public Expression evaluate(FunctionExpression input, List<Expression> parameters, Expression evaluatedParameter, LessProblems problems) {
    return new IdentifierExpression(input.getUnderlyingStructure(), "fixed");
  }
  
}

Use the Configuration object to pass your new function to the compiler:

Configuration configuration = new Configuration();
configuration.addCustomFunction(new ConstantFunction());

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

Use it on following less:

div {
  property: constant();
}

to obtain:

div {
  property: fixed;
}
  • custom functions are called before build-in functions,
  • use clone,

Clone this wiki locally