String templates / formatting strings


I am new to Zig. I want to read a template string from a config file an replace certain markers with the value of variables Just like the print statement, just that the format is not known at comptime. Is there something like that in Zig/C?

Kind Regards

There are some libraries but I did not test them: Growing a {{mustache}} with Zig - Zig NEWS GitHub - MasterQ32/ZTT: Precompiled Zig text template engine

1 Like

Thanks a lot. I will add that to my bookmarks.
Since the template string is pretty simple (one line) I think sprintf from stdio.h just might do the trick (although it introduces the dependency on libc).

To mimic sprintf, you could look at std.fmt.bufPrint or std.fmt.allocPrint

For example :

var buf: [1024]u8 = undefined;
const fmt_buf = try std.fmt.bufPrint(&buf, 
                                     "I am {d} old and my name is {s}", 
                                     .{42, "Averell"}
std.debug.print("{s}\n", .{fmt_buf});

Same with allocPrint, which needs an allocator – maybe too much if your template is simple…

// with Allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const alloc = gpa.allocator();
    defer _ = gpa.deinit();

    const alloc_buf = try std.fmt.allocPrint(alloc, 
                                             "I am {d} old and my name is {s}",
                                             .{42, "Averell"}

    std.debug.print("{s}\n", .{alloc_buf});

I store the template string in a config file. In both those functions fmt has to be comptime known.

Ooops, sorry… I was focused on the “sprintf” replacement and forgot the non comptime requirement.