Skip to content

Commit cb89dd3

Browse files
committed
feat(backend): template support for subpath
1 parent d254a3f commit cb89dd3

2 files changed

Lines changed: 12 additions & 8 deletions

File tree

src/App.zig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,9 @@ fn captureAccess(ctx: *Context, req: *httpz.Request, res: *httpz.Response) !void
205205
};
206206
defer parsed.deinit(ctx.allocator);
207207

208-
response_template.render(parsed, req, writer) catch |err| {
208+
const context = response_template.Context{ .request = req, .subpath = subpath };
209+
210+
response_template.render(parsed, &context, writer) catch |err| {
209211
try writer.print("Failed to render template: {any}", .{err});
210212
res.setStatus(.internal_server_error);
211213
res.content_type = .TEXT;

src/response_template.zig

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ const httpz = @import("httpz");
44

55
const Template = @import("Template.zig");
66

7-
const RequestVariables = struct {
7+
pub const Context = struct {
88
request: *httpz.Request,
9+
subpath: []const u8,
910

1011
fn print(context: *const anyopaque, writer: *std.Io.Writer, name: []const u8) anyerror!bool {
11-
const self: *const RequestVariables = @ptrCast(@alignCast(context));
12+
const self: *const Context = @ptrCast(@alignCast(context));
1213
var split = std.mem.splitScalar(u8, name, '.');
1314

1415
const first = split.next().?;
@@ -61,14 +62,17 @@ const RequestVariables = struct {
6162
} else {
6263
try writer.writeAll(cookies.header);
6364
}
65+
} else if (std.mem.eql(u8, first, "subpath")) {
66+
if (optional_second != null) return false;
67+
try writer.writeAll(self.subpath);
6468
} else {
6569
return false;
6670
}
6771

6872
return true;
6973
}
7074

71-
fn variables(self: *const RequestVariables) Template.Variables {
75+
fn variables(self: *const Context) Template.Variables {
7276
return .{
7377
.context = @ptrCast(self),
7478
.vtable = &.{
@@ -78,9 +82,7 @@ const RequestVariables = struct {
7882
}
7983
};
8084

81-
pub fn render(template: Template, request: *httpz.Request, writer: *std.Io.Writer) !void {
82-
const request_variables = RequestVariables{ .request = request };
83-
const variables = request_variables.variables();
84-
85+
pub fn render(template: Template, context: *const Context, writer: *std.Io.Writer) !void {
86+
const variables = context.variables();
8587
try template.render(writer, variables, .{});
8688
}

0 commit comments

Comments
 (0)