MustacheTemplates.fromDirectory constructor

MustacheTemplates.fromDirectory(
  1. String directory, {
  2. String extension = '.html',
})

Loads every file under directory whose name ends with extension.

A template's name is its path below directory without the extension, so web/templates/mail/welcome.html is mail/welcome.

That name works for render. It does not work in a {{> partial}} tag: mustache_template allows only letters, digits, -, _ and . there, so a fragment meant to be included has to sit at the root or carry a flat name. A slash in a partial tag fails at load time rather than silently rendering nothing.

Implementation

factory MustacheTemplates.fromDirectory(
  String directory, {
  String extension = '.html',
}) {
  final root = Directory(directory);
  if (!root.existsSync()) {
    throw ArgumentError('no template directory at "$directory"');
  }

  final sources = <String, String>{};
  for (final entry in root.listSync(recursive: true).whereType<File>()) {
    if (!entry.path.endsWith(extension)) continue;

    final relative = entry.path
        .substring(root.path.length)
        .replaceAll(r'\', '/')
        .replaceFirst(RegExp('^/'), '');
    final name = relative.substring(0, relative.length - extension.length);
    sources[name] = entry.readAsStringSync();
  }
  return MustacheTemplates(sources);
}