template_cache 0.1.1

  • README.md
  • Installing
  • Versions
  • 0

Template Cache for Dart

Templates in Dart can be implemented in different ways:

1. Parsing at runtime

This approach is the most straightforward approach, requiring no special compiling. This can be bad for performance, though. To counterweight that, templating languages implemented in this way can end up lacking in features instead.

2. Static precompilation

For static pages, all templates can be rendered ahead of time. This is great for performance since all the complexity is handled at build time. However, this means that logic cannot be computed at runtime.

3. Precompilation into Dart

The third way to do it is to precompile the templates into native Dart code, which will be super fast at runtime, and can be built into the main code base using Dart2JS for production. This can be confusing, though, because Dart files must be imported in the source code.

Usage

This library simplifies option 3 from above. Here's how to use it:

Consider this project.

├── bin
│   └── server.dart
├── templates
│   └── my_template.some_ext
├── tool
│   └── compile_templates.dart
└── web
    ├── index.html
    └── index.dart

In this example, we keep the templates in a templates directory.

To compile our templates, we run dart tool/compile_templates.dart:

import 'package:template_cache/cache.dart';
import 'package:SOME_PACKAGE_THAT_GIVES_US_A_COMPILER';

final cache = new Cache([
  new SomeThirdPartyCompiler() // <-- This compiler compiles ".some_ext" files
]);

main() async {
  await cache.compile('templates/my_template.some_ext');
}

Now, to render the template, in both the web/main.dart or bin/server.dart files, we can simply use the render function:

import 'package:template_cache/render.dart';

main() {
  var view = render('templates/my_template.some_ext');
}

The render function returns a Stream<String>, so that compilers can incorporate asynchrony in the most performant way.

If the compiler supports it, render has a named locals parameter, accepting variables into the template. The locals are supplied as Map<Symbol, dynamic>.

render('my_template.hbs', locals: {
  #someVariable: "some value"
});

Note: Using symbols rather than strings as keys allows the template code to access locals directly without using mirrors. This is explained below.

Compilers

A compiler must satisfy a simple contract, and can take configuration in its constructor, since that will be exposed to the consumer (as shown above).

The compile method in the contract returns a special GeneratedTemplateCode data object, containing the generated code as two strings. The first one contains imports for the generated script. The second contains the main render method body, in a async* context.

import 'dart:async';

import 'package:template_cache/cache.dart';

class MyCompiler implements Compiler {
  final ContentType contentType = ContentType.HTML; // Supplied for use with servers
  final Iterable<String> extensions = ['.my_ext', '.my_other_ext'];

  Future<GeneratedTemplateCode> compile(Uri file, Stream<String> source) async {
    // Use the [file] and [source] arguments to generate the code

    return new GeneratedTemplateCode(
      '''
        import "some_specific_import_that_the_template_will_require" as package;
      ''',

      r'''
        yield r"A line!\n";

        yield someLocal + r'\n';

        package.someImportedMethod();

        if (someBooleanLocal) {
          yield r"A conditional line!\n";
        }
      '''
    );
  }
}

Using the above MyCompiler, the workflow would be something like this:

Build time

final cache = new Cache([
  new MyCompiler()
]);

cache.compile('some_template.my_ext');

Runtime

render('some_template.my_ext', {
  #someLocal: 'Hello, World!',
  #someBooleanLocal: true
});

Output

A line!
Hello, World!
A conditional line!

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  template_cache: ^0.1.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:template_cache/cache.dart';
import 'package:template_cache/html_compiler.dart';
import 'package:template_cache/plain_text_compiler.dart';
import 'package:template_cache/render.dart';
  
Version Uploaded Documentation Archive
0.1.1 Sep 16, 2016 Go to the documentation of template_cache 0.1.1 Download template_cache 0.1.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
--
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
--
Overall:
Weighted score of the above. [more]
0
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Fix dependencies in pubspec.yaml.

Running pub upgrade failed with the following output:

ERR: The current Dart SDK version is 2.1.0.
 
 Because template_cache depends on current_script >=0.0.2 which requires SDK version <2.0.0, version solving failed.

Health suggestions

Format bin/clean.dart.

Run dartfmt to format bin/clean.dart.

Format lib/cache.dart.

Run dartfmt to format lib/cache.dart.

Format lib/plain_text_compiler.dart.

Run dartfmt to format lib/plain_text_compiler.dart.

Fix additional 7 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/_gen/templates.dart (Run dartfmt to format lib/src/_gen/templates.dart.)
  • lib/src/cache.dart (Run dartfmt to format lib/src/cache.dart.)
  • lib/src/cache_io.dart (Run dartfmt to format lib/src/cache_io.dart.)
  • lib/src/codegen_contract.dart (Run dartfmt to format lib/src/codegen_contract.dart.)
  • lib/src/render.dart (Run dartfmt to format lib/src/render.dart.)
  • lib/src/simple_compiler_base.dart (Run dartfmt to format lib/src/simple_compiler_base.dart.)
  • lib/src/uid.dart (Run dartfmt to format lib/src/uid.dart.)

Maintenance issues and suggestions

Add SDK constraint in pubspec.yaml. (-50 points)

For information about setting SDK constraint, please see https://www.dartlang.org/tools/pub/pubspec#sdk-constraints.

Fix platform conflicts. (-20 points)

Error(s) prevent platform classification:

Fix dependencies in pubspec.yaml.

Running dartdoc failed. (-10 points)

Make sure dartdoc runs without any issues.

Package is too old. (-100 points)

The package was released more than two years ago.

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use template_cache.dart.