platform/packages/html/lib/angel3_html.dart

37 lines
1.1 KiB
Dart
Raw Normal View History

2017-07-23 15:50:37 +00:00
import 'dart:async';
2021-09-11 04:03:14 +00:00
import 'package:angel3_framework/angel3_framework.dart';
import 'package:belatuk_html_builder/belatuk_html_builder.dart';
2017-07-23 15:50:37 +00:00
/// Returns a [RequestMiddleware] that allows you to return `html_builder` [Node]s as responses.
///
/// You can provide a custom [renderer]. The default renders minified HTML5 pages.
///
/// Set [enforceAcceptHeader] to `true` to throw a `406 Not Acceptable` if the client doesn't accept HTML responses.
2021-09-11 04:03:14 +00:00
RequestHandler renderHtml(
{StringRenderer? renderer, bool? enforceAcceptHeader}) {
2021-06-20 12:37:20 +00:00
renderer ??= StringRenderer(pretty: false, html5: true);
2017-07-23 15:50:37 +00:00
return (RequestContext req, ResponseContext res) {
var oldSerializer = res.serializer;
res.serializer = (data) {
2021-06-20 12:37:20 +00:00
if (data is! Node) {
2021-09-11 04:03:14 +00:00
return oldSerializer(data);
2021-06-20 12:37:20 +00:00
} else {
if (enforceAcceptHeader == true && !req.accepts('text/html')) {
throw AngelHttpException.notAcceptable();
}
2017-07-23 15:50:37 +00:00
2021-06-20 12:37:20 +00:00
var content = renderer!.render(data);
2017-07-23 15:50:37 +00:00
res
..headers['content-type'] = 'text/html'
2019-01-06 18:11:11 +00:00
..write(content);
res.close();
2017-07-23 15:50:37 +00:00
return '';
}
};
2021-06-20 12:37:20 +00:00
return Future<bool>.value(true);
2017-07-23 15:50:37 +00:00
};
}