zigzap / zap

blazingly fast backends in zig
MIT License
2.17k stars 72 forks source link

How to serve an html template from a file? #124

Open ally9335 opened 3 weeks ago

ally9335 commented 3 weeks ago

There's no example in /examples but one for encoding it as Zig code.

jeroenflvr commented 3 weeks ago

Mustache has a 'fromFile()' method.

importing mustache

const Mustache = @import("zap").Mustache;

and then just call fromFile()

var mustache = Mustache.fromFile("view/layout/base.html") catch return;
defer mustache.deinit();

const ret = mustache.build(.{});
defer ret.deinit();

if (r.setContentType(.HTML)) {
    if (ret.str()) |s| {
        r.sendBody(s) catch return;;
    } else {
        r.sendBody("<html><body><h1>mustacheBuild() failed!</h1></body></html>") catch return;
    }
} else |err| {
    std.debug.print("Error while setting content type: {}\n", .{err});
}