parseDataTree function

Future<Map<String, Object?>> parseDataTree(
  1. Config config, {
  2. String? path,
})

Parse all YAML and JSON files inside data_dir and create data Map which you can access inside templates.

Each subfolder inside data_dir becomes a key inside the returned Map<String, dynamic>. Therefore it does not matter if you use single file with deeply nested data or split the data into more files (data tree will be the same).

See example directory for reference.

Implementation

Future<Map<String, Object?>> parseDataTree(
  Config config, {
  String? path,
}) async {
  final data = <String, Object?>{};
  path ??= config.build.dataDir;
  final nodes = await fs.directory(path).list().toList();

  for (final e in nodes) {
    await e.when(
      directory: (directory) async {
        final name = Path.basename(directory.path);
        data[name] = await parseDataTree(config, path: directory.path);
      },
      file: (file) async {
        final name = Path.basenameWithoutExtension(file.path);
        try {
          final dynamic content = await _parseData(file) as dynamic;
          data[name] = content;
        } catch (e) {
          log.error(e);
        }
      },
    );
  }

  return data;
}