template_expressions 1.1.1 copy "template_expressions: ^1.1.1" to clipboard
template_expressions: ^1.1.1 copied to clipboard

outdated

A Dart library to process string based templates using expressions.

template_expressions #

Table of Contents #

Introduction #

A Dart library to process string based templates using expressions.

Using the Library #

Add the repo to your Dart pubspec.yaml file.

dependencies:
  template_expressions: <<version>> 

Then run...

dart pub get

Template Expression Syntax #

The template engine supports different syntax options for how the expressions are discovered within the template. There are three built in syntax options as described below. To provide your own syntax, simple implement the ExpressionSyntax class and pass that to the template at construction.

HashExpressionSyntax #

The hash expression syntax begins and ends with a double hash symbol. This syntax is compatible with many different forms of code and text file templates without much need for escape characters.

Example

{
  "firstName": "##firstName.toUpperCase()##",
  "lastName": "##lastName.toUpperCase()##"
}

MustacheExpressionSyntax #

The mustache expression syntax begins with a double open curly brace and ends with a double close curley brace. This syntax is relatively common as it is a highly simplified version of the mustache template. Only the double curly braces are supported, no other aspects of the mustache syntax are.

Example

{
  "firstName": "{{firstName.toUpperCase()}}",
  "lastName": "{{lastName.toUpperCase()}}"
}

PipeExpressionSyntax #

The pipe expression syntax begins and ends with a single pipe symbol. This syntax is compatible with many different forms of code and text file templates without much need for escape characters.

Example

{
  "firstName": "|firstName.toUpperCase()|",
  "lastName": "|lastName.toUpperCase()|"
}

StandardExpressionSyntax #

The standard expression syntax follows the Dart string interpolation pattern. This is the default syntax all templates will use unless a separate syntax list is provided. It is the default as it is likely to be the most familiar with Dart developers, however it also has some conflicts that require special escaping. In Dart code, either the dollar sign must be escaped \${...} or the string must be tagged as a regular string (r'...'). In all forms, if there is a map defined in the expression, the close curly braces must be escaped like: r'${createName({"firstName": "John", "lastName": "Smith"\})}

Example

{
  "firstName": "${firstName.toUpperCase()}",
  "lastName": "${lastName.toUpperCase()}"
}

Built in Objects and Members #

Codex #

The Codex class is supported for encoding and decoding values.

Example

base64.encode(value)
hex.encode(value)
json.encode(value)
utf8.encode(value)

base64.decode(value)
hex.decode(value)
json.decode(value)
utf8.decode(value)

Member Functions

Function Example
decode ${base64.decode(value)
encode ${base64.encode(value)

DateFormat #

The DateFormat class is supported for parsing and formatting functions.

Constructors

DateFormat(String format)

Member Functions

Function Example
format ${DateFormat('yyyy-MM-dd').format(now())}
parse ${DateFormat('yyyy-MM-dd').parse('2022-01-01')}
parseUTC ${DateFormat('yyyy-MM-dd').parseUTC('2022-01-01')}
parseUtc ${DateFormat('yyyy-MM-dd').parseUtc('2022-01-01')}

DateTime #

The DateTime class is supported for performing date time related functionality.

Constructors

now()
DateTime(int utcMillis)
DateTime(int year, int month, [int date, int hour, int minute, int second, int millisecond])
DateTime({int year, int month, int date, int hour, int minute, int second, int millisecond})
DateTime(List<int> yearMonthDateHourMinuteSecondMillisecond)

Global Functions

Function Description Example
now Alias for the dart code of DateTime.now() ${now()}

Member Functions

Function Example
add ${now().add(minutes(5))}
add(int millis) ${now().add(30000)}
compareTo ${now().compareTo(other)}
isAfter ${now().isAfter(other)}
isBefore ${now().isBefore(other)}
isUtc ${now().isUtc}
millisecondsSinceEpoch ${now().millisecondsSinceEpoch}
subtract ${now().subtract(minutes(5))}
subtract(int millis) ${now().subtract(30000)}
toIso8601String ${now().toIso8601String()}
toLocal ${now().toLocal()}
toUtc ${now().toUtc()}

Duration #

The Duration class is supported for duration related calculations.

Constructors

now()
Duration(int milliseconds)
DateFormat(int days, int hours, [int minutes, int seconds, int milliseconds])
DateFormat({int days, int hours, [int minutes, int seconds, int milliseconds})
DateFormat(List<int> daysHoursMinutesSecondsMilliseconds)

Global Functions

Function Description Example
days(int value) Alias for Duration({"days": value}) ${days(5).inMilliseconds}
hours(int value) Alias for Duration({"hours": value}) ${hours(5).inMilliseconds}
milliseconds(int value) Alias for Duration({"milliseconds": value}) ${milliseconds(5000).inSeconds}
minutes(int value) Alias for Duration({"minutes": value}) ${minutes(5).inMilliseconds}
seconds(int value) Alias for Duration({"seconds": value}) ${seconds(5).inMilliseconds}

Member Functions

Function Example
add(Duration duration) ${Duration(1000).add(minutes(5))}
add(int milliseconds) ${Duration(1000).add(1000)}
compareTo ${Duration(1000).compareTo(other)}
inDays ${Duration({"hours": 48}).inDays}
inHours ${Duration(30000).inHours}
inMilliseconds ${Duration(30000).inMilliseconds}
inMinutes ${Duration(30000).inMinutes}
inSeconds ${Duration(30000).inSeconds}
subtract(Duration duration) ${Duration({minutes: 5}).subtract(seconds(5))}
subtract(int milliseconds) ${Duration({minutes: 5}).subtract(5000)}

Iterable #

Several member functions from the Iterable class are supported.

Member Functions

Function Example
contains ${value.contains('string')}
elementAt ${value.elementAt(1)}
first ${value.first}
isEmpty ${value.isEmpty ? 'null' : value.first}
isNotEmpty ${value.isNotEmpty ? value.first : 'null'}
last ${value.last}
length ${value.length}
join ${value.join(',')}
single ${value.single}
skip ${value.skip(1).join(',')}
take ${value.take(3).join(',')}
toList ${value.toList().sort()}
toSet ${value.toSet().first}

List

In addition to the items supported by the Iterable class, a List additionally supports the following functions...

Member Functions

Function Example
asMap ${list.asMap()[2]}
reversed ${list.reversed.first}
sort ${list.sort().first}

JsonPath #

The JsonPath class is supported to allow for walking JSON-like values.

Constructors

JsonPath(String expression)

Global Functions

Function Description Example
json_path(dynamic value, String path) Alias for JsonPath(path).read(value).first.value ${json_path(object, '$.person.firstName')}

Member Functions

Function Example
read ${JsonPath('$.person.firstName').read(obj).first.value}
readValues ${JsonPath('$.person.firstName').values(obj).first}

JsonPathMatch #

The JsonPathMatch class is supported to allow for walking JSON-like values. It is unlikely you will want to create this class yourself and it is expected it will come from using JsonPath.

Member Functions

Function Example
parent ${JsonPath('$.person.firstName').read(obj).first.parent.value}
path ${JsonPath('$.person.firstName').read(obj).first.path}
value ${JsonPath('$.person.firstName').read(obj).first.value}

Map #

The following Map members are supported.

Member Functions

Function Example
containsValue ${map.containsValue('value')}
keys ${map.keys.first}
isEmpty ${map.isEmpty ? 'null' : map.values.first}
isNotEmpty ${map.isNotEmpty ? map.values.first : 'null'}
length ${map.length}
remove ${map.remove('key')}
values ${map.values.first}

num #

The following num members are supported.

Member Functions

Function Example
abs ${number.abs()}
ceil ${number.ceil()}
ceilToDouble ${number.ceilToDouble()}
clamp ${number.clamp(lower, upper)}
compareTo ${number.compareTo(other)}
floor ${number.floor()}
floorToDouble ${number.floorToDouble()}
isFinite ${number.isFinite}
isInfinte ${number.isInfinte}
isNaN ${number.isNaN}
isNegative ${number.isNegative}
remainder ${number.remainder(other)}
round ${number.round()}
roundToDouble ${number.roundToDouble}
sign ${number.sign}
toDouble ${number.toDouble()}
toInt ${number.toInt()}
toStringAsExponential ${number.toStringAsExponential(fractionDigits)}
toStringAsFixed ${number.toStringAsFixed(fractionDigits)}
toStringAsPrecision ${number.toStringAsPrecision(precision)}
truncate ${number.truncate()}
truncateToDouble ${number.truncateToDouble()}

String #

The following String members are supported.

Member Functions

Function Example
compareTo ${str.compareTo(other)}
contains ${str.contains('other')}
endsWith ${str.endsWith('other')}
indexOf ${str.indexOf('other')}
isEmpty ${str.isEmpty ? 'null' : str}
isNotEmpty ${str.isNotEmpty ? str : 'null'}
lastIndexOf ${str.lastIndexOf('/')}
length ${str.length}
padLeft ${str.padLeft(2, ' ')}
padRight ${str.padRight(2, ' ')}
replaceAll ${str.replaceAll('other', 'foo')}
replaceFirst ${str.replaceFirst('other', 'foo')}
split ${str.split(',').join('\n')}
startsWith ${str.startsWith('other')}
substring ${str.substring(begin, end)}
toLowerCase ${str.toLowerCase()}
toUpperCase ${str.toUpperCase()}
trim ${str.trim()}
trimLeft ${str.trimLeft()}
trimRight ${str.trimRight()}

Object #

The following Object members are supported.

Member Functions

Function Example
hashCode ${obj.hashCode}
runtimeType ${obj.runtimeType.toString()}
toString ${obj.toString()}