ykmnkmi / jinja.dart

Jinja2 template engine port for Dart.
https://pub.dev/packages/jinja
MIT License
51 stars 11 forks source link

Loading templates from assets folder in Flutter #11

Closed benboughton1 closed 2 years ago

benboughton1 commented 2 years ago

Hello - I am having issues storing templates and loading them. I am running app in android simulator.

My pubspec.yaml:

    - assets/
    - assets/templates/users.html
    - assets/templates/layouts/

var path = Platform.script.resolve('assets/templates').toFilePath(); and var path = Directory.current.uri.resolve('assets/templates').toFilePath();

Loading path into FileSystemLoader then try running example template (users.html) or even env.ListTemplates gives an empty list.

I am I doing something wrong or is there a gotcha when I use Flutter that I am not aware of?

ykmnkmi commented 2 years ago

Hello, you need to use Flutter rootBundle, which is asynchronous, and upload files to MapLoader. Сan write example later.

benboughton1 commented 2 years ago

That would be great! I tried with rootBundle but couldn't quite figure it out.

On Sat, 23 Apr 2022, 2:58 pm Olzhas Suleimen, @.***> wrote:

Hello, you need to use Flutter rootBundle, which is asynchronous, and upload files to MapLoader. Сan write example later.

— Reply to this email directly, view it on GitHub https://github.com/ykmnkmi/jinja.dart/issues/11#issuecomment-1107362082, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAQEGDYJ3RQKDSKPGTZLMILVGN7O7ANCNFSM5UCRAAGA . You are receiving this because you authored the thread.Message ID: @.***>

benboughton1 commented 2 years ago

I noticed you wrote some helpful code comments for MapLoader in latest release. That got me sorted. Example below.

  setupJijna() async {
    var index = await rootBundle.loadString('assets/templates/users.html');
    var layout = await rootBundle.loadString('assets/templates/layouts/base.html');

    var loader = MapLoader({'users.html': index, 'layouts/base.html': layout});

    return Environment(
      globals: <String, Object?>{
        'now': () {
          var dt = DateTime.now().toLocal();
          var hour = dt.hour.toString().padLeft(2, '0');
          var minute = dt.minute.toString().padLeft(2, '0');
          return '$hour:$minute';
        },
      },
      autoReload: true,
      loader: loader,
      leftStripBlocks: true,
      trimBlocks: true,
    );
  }