Jinja View Template for Angel3

Pub Version (including pre-releases) Null Safety Discord License

A service that renders Jinja2 view template into HTML for Angel3 framework. Ported from Python to Dart.

Installation

In your pubspec.yaml:

dependencies:
  angel3_jinja: ^10.0.0

Usage

import 'dart:io';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_jinja/angel3_jinja.dart';
import 'package:path/path.dart' as p;

void main() async {
  var app = Angel();
  var http = AngelHttp(app);
  var viewsDir = p.join(
    p.dirname(
      p.fromUri(Platform.script),
    ),
    'views',
  );

  // Enable Jinja2 views
  await app.configure(jinja(path: viewsDir));

  // Add routes.
  // See: https://github.com/ykmnkmi/jinja.dart/blob/master/example/bin/server.dart

  app
    ..get('/', (req, res) => res.render('index.html'))
    ..get('/hello', (req, res) => res.render('hello.html', {'name': 'user'}))
    ..get('/hello/:name', (req, res) => res.render('hello.html', req.params));

  app.fallback((req, res) {
    res
      ..statusCode = 404
      ..write('404 Not Found :(');
  });

  // Start the server
  await http.startServer('127.0.0.1', 3000);
  print('Listening at ${http.uri}');
}

Escaping

Values are not HTML-escaped. Escape every value that is not trusted HTML, such as one from the request, with the e (or escape) filter:

<p>hello {{ name | e }}!</p>

Views

A view name that resolves outside the views directory (../secret.html, an absolute path, a symbolic link out of it), that has none of the extensions in ext, or that does not exist, is a 404. In production, templates are kept parsed; otherwise they are read again on every render.

Migrating from 9.x to 10.0.0

The breaking changes of each release are listed in the CHANGELOG. Those of 10.0.0 that may need changes in an app:

  • Views outside the views directory: a view or included template that resolves outside the views directory (../secret.html, an absolute path, a symbolic link out of it), or has none of the extensions in ext, is not found. A view that is not found throws a 404 AngelHttpException instead of TemplateNotFound, also with a custom createLoader.
  • Symbolic links: with followLinks: false, a symbolic link within the views directory is not followed.
  • Production: in production, templates are kept parsed, so changes to them are seen only after the app restarts.
  • Requires angel3_framework 10.

Libraries

angel3_jinja