Zig 生態中的模板語言

模板語言在動態內容生成方面比手動編寫代碼具有許多優勢,這使得它們在各種用例中必不可少。主要場景有:

在 Zig 生態中,目前主要有如下兩個實現:

const std = @import("std");
const mustache = @import("mustache");

pub fn main() !void {
    const template =
        \\Hello {{name}} from Zig
        \\Supported features:
        \\{{#features}}
        \\  - {{name}}
        \\{{/features}}
    ;

    const data = .{
        .name = "friends",
        .features = .{
            .{ .name = "interpolation" },
            .{ .name = "sections" },
            .{ .name = "delimiters" },
            .{ .name = "partials" },
        },
    };

    const allocator = std.testing.allocator;
    const result = try mustache.allocRenderText(allocator, template, data);
    defer allocator.free(result);

    try std.testing.expectEqualStrings(
        \\Hello friends from Zig
        \\Supported features:
        \\  - interpolation
        \\  - sections
        \\  - delimiters
        \\  - partials
        \\
    , result);
}
// src/templates/example.zmpl

if (std.mem.eql(u8, "zmpl is simple""zmpl" ++ " is " ++ "simple")) {
  <div>Email: {.user.email}</div>
  <div>Token: {.auth.token}</div>
}

// main.zig
const zmpl = @import("zmpl");
const manifest = @import("templates/zmpl.manifest.zig"); // Auto-generated by Zmpl.

test "readme example" {
    var data = zmpl.Data.init(allocator);
    defer data.deinit();

    var body = try data.object();
    var user = try data.object();
    var auth = try data.object();

    try user.put("email", data.string("user@example.com"));
    try auth.put("token", data.string("abc123-456-def"));

    try body.put("user", user);
    try body.put("auth", auth);

    const output = try manifest.templates.example.render(&data);
    defer allocator.free(output);

    try std.testing.expectEqualStrings(
        \\  <div>Email: user@example.com</div>
        \\  <div>Token: abc123-456-def</div>
        \\
    , output);
}

引用鏈接

[1] mustache-zig: https://github.com/batiati/mustache-zig
[2] zmpl: https://github.com/jetzig-framework/zmpl

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/ADxp5vta-40itfNLYzqfig