From 25cd5f982bb3cc74d6c0b730cb796954b99f00ab Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Sat, 10 Dec 2022 02:44:54 -0800 Subject: [PATCH] Escape HTML --- src/template/lib.zig | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/template/lib.zig b/src/template/lib.zig index 33b55d3..9aa1cf0 100644 --- a/src/template/lib.zig +++ b/src/template/lib.zig @@ -7,7 +7,7 @@ pub fn main() !void { .{ .test_tmpl = "{.x} {%context_foo}" }, @embedFile("./test.tmp.html"), .{ - .community = .{ .name = "abcd" }, + .community = .{ .name = "" }, .foo = [_][]const u8{ "5", "4", "3", "2", "1" }, .baz = [_][]const []const u8{ &.{ "5", "4", "3", "2", "1" }, @@ -184,9 +184,19 @@ fn executeStatement( } } +fn htmlEscape(writer: anytype, str: []const u8) !void { + for (str) |ch| switch (ch) { + '<' => try writer.writeAll("<"), + '>' => try writer.writeAll(">"), + '"' => try writer.writeAll("""), + '&' => try writer.writeAll("&"), + else => try writer.writeByte(ch), + }; +} + fn print(writer: anytype, arg: anytype) !void { const T = @TypeOf(arg); - if (comptime std.meta.trait.isZigString(T)) return writer.writeAll(arg); + if (comptime std.meta.trait.isZigString(T)) return htmlEscape(writer, arg); if (comptime std.meta.trait.isNumber(T)) return std.fmt.format(writer, "{}", .{arg}); @compileLog(@TypeOf(arg));