Jinja for Dart

Pub

Jinja server-side template engine port for Dart 2. Variables, expressions, control structures and template inheritance.

Breaking changes

Before object.field or object.method() expressions uses dart:mirrors methods.

import 'package:jinja/jinja.dart';

// ...

final environment = Environment( /* ... */ );
final template = environment.fromString('{{ users[0].name }}');

// ...

outStringSink.write(template.render(users: listOfUsers));
// outStringSink.write(template.renderMap({'users': listOfUsers}));

Now to access the fields and methods of the object, (except namespase, loop, self fields and methods), you need to write your own method or import the get_field method from the package:jinja/get_field.dart file and pass it to the Environment constructor.
Or write and pass your method, like here.

import 'package:jinja/jinja.dart';
import 'package:jinja/get_field.dart' show getField;

// ...

final environment = Environment(getField: getField, /* ... */ );
final template = env.fromString('{{ users[0].name }}');

// ...

outStringSink.write(template.render(users: listOfUsers));
// outStringSink.write(template.renderMap({'users': listOfUsers}));

Done

  • Loaders
    • FileSystemLoader
    • MapLoader (DictLoader)
  • Comments
  • Variables
  • Expressions: variables, literals, subscription, math, comparison, logic, tests, filters, calls
  • Filters (not all, see here)
  • Tests
  • Statements
    • Filter
    • For (without recursive)
    • If
    • Set
    • Raw
    • Inlcude
    • Extends
    • Block

Example

Add package to your pubspec.yaml as a dependency

dependencies:
  jinja: ^0.2.0

Import library and use it:

import 'package:jinja/jinja.dart';

// code ...

final environment = Environment(blockStart: '...');
final template = env.fromString('...source...');

outStringSink.write(template.render(key: value));
// outStringSink.write(template.renderMap({'key': value}));

Note

Why is this hack used?

In the final version, templates will be generated by antotation or pub binary and the render function will have named parameters that are used in the template. Working and testing here.

Example:

<!-- user.html -->
<p>hello {{ name }}!</p>

will transformed to:

import 'package:renderable/renderable.dart';

class UserTemplate implements Template {
  const UserTemplate();

  @override
  String render({Object name}) {
    final buffer = StringBuffer();
    buffer.write(_t0);
    buffer.write(name);
    buffer.write(_t1);
    return buffer.toString();
  }

  // or with optimizations to

  @override
  String render({Object name}) {
   return '<p>hello $name!</p>';
  }

  static const String _t0 = '<p>hello ';

  static const String _t1 = '!</p>';
}

Contributing

If you found a bug, just create a new issue or even better fork and issue a pull request with your fix.

Libraries

get_field
jinja