模板语言在动态内容生成方面比手动编写代码具有许多优势,这使得它们在各种用例中必不可少。主要场景有:
• Web 开发: 使用模板语言可以动态生成 HTML 页面,例如根据数据库中的数据显示产品列表或用户个人资料。
• 电子邮件营销: 模板语言可用于创建个性化的电子邮件,其中包含针对特定用户的动态内容。
• 文档生成: 模板语言可用于生成各种文档,例如报告、演示文稿和用户指南。
• 配置文件管理: 模板语言可用于生成配置文件和其他基于文本的配置数据。
在 Zig 生态中,目前主要有如下两个实现:
• mustache-zig[1]:Logic-less templates for 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);
}
• zmpl[2]:a templating language written in Zig。用法如下:
// 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