Allow responding to HTML when no template present

If no template present, allow the request to render the view and then
only render a 404 if the view does not redirect, otherwise all views
would need a placeholder Zmpl template even if the view does not use it.

Also parse HTTP body as query string if present.
This commit is contained in:
Bob Farrell 2024-04-02 22:15:18 +01:00
parent b94845a415
commit eed58edeba
2 changed files with 18 additions and 9 deletions

View File

@ -258,7 +258,8 @@ fn queryParams(self: *Self) !*jetzig.data.Value {
}
fn parseQueryString(self: *Self) !bool {
if (self.path.query) |query| {
const data: ?[]const u8 = if (self.body.len > 0) self.body else self.path.query;
if (data) |query| {
self.query.* = jetzig.http.Query.init(
self.allocator,
query,

View File

@ -144,12 +144,18 @@ fn renderHTML(
route: ?*jetzig.views.Route,
) !void {
if (route) |matched_route| {
if (zmpl.find(matched_route.template)) |template| {
const rendered = self.renderView(matched_route, request, template) catch |err| {
if (isUnhandledError(err)) return err;
const rendered_error = try self.renderInternalServerError(request, err);
return request.setResponse(rendered_error, .{});
};
const template = zmpl.find(matched_route.template);
if (template == null) {
if (try self.renderMarkdown(request, route)) |rendered_markdown| {
return request.setResponse(rendered_markdown, .{});
}
}
const rendered = self.renderView(matched_route, request, template) catch |err| {
if (isUnhandledError(err)) return err;
const rendered_error = try self.renderInternalServerError(request, err);
return request.setResponse(rendered_error, .{});
};
if (request.status_code != .not_found) {
return request.setResponse(rendered, .{});
}
}
@ -265,8 +271,10 @@ fn renderView(
.content = try self.renderTemplateWithLayout(request, capture, rendered_view, route),
};
} else {
// We are rendering JSON, content is the result of `toJson` on view data.
return .{ .view = rendered_view, .content = "" };
return switch (request.requestFormat()) {
.HTML, .UNKNOWN => try renderNotFound(request),
.JSON => .{ .view = rendered_view, .content = "" },
};
}
} else {
try self.logger.WARN("`request.render` was not invoked. Rendering empty content.", .{});