Skip to content

Formatter Operators

JPVenson edited this page Dec 26, 2021 · 8 revisions

Please note: Operator formatters are still considered an Experimental feature. That means that there are possible some bugs present that are not covered by any test

Operators are considered a special kind of formatters. They are not invoked via the Path.Formatter() syntax but instead uses special characters. You have to implement operators by yourself. A list of predefined operators can be found in the list of all Formatters: https://github.com/JPVenson/morestachio/wiki/Predefined-Formatter

To define a custom operator you have to create a formatter function that declares the MorestachioOperatorAttribute and set the desired operator enum. The Enum values are then translated in the template to the corresponding operator char/s, like OperatorTypes.Add can be invoked by calling {{Data + Data}} in your template. As Operators are currently directly associated with certain special chars, the list of possible operators are limited please see the mapping in MorestachioOperator.cs

Operators follow the Left-To-Right logic. That means that an chained operator like this {{A + B + C}} will be executed as follows:

  • Get value from A -> AVal
  • Get value from B -> BVal
  • AVal + BVal = ABVal
  • Get value from C -> CVal
  • ABVal + CVal

To encase certain operators you can also use brackets in your expressions like this:: {{A + (B + C)}}. This will be executed as follows:

  • Get value from A -> AVal
  • Get Arguments for ():
    • Get value from B -> BVal
    • Get value from C -> CVal
    • BVal + CVal -> BCVal
    • Call Self with BCVal -> SelfVal
  • AVal + SelfVal

The current parsing of operators is lazy. That means that chained operators might not in all cases be correctly evaluated. A expression like e > 5 && e < 8 will be falsely parsed as ((e > 5) && e) < 8. For a workaround Please see issue #20