Zig 生態中的模板語言
模板語言在動態內容生成方面比手動編寫代碼具有許多優勢,這使得它們在各種用例中必不可少。主要場景有:
-
• 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
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/ADxp5vta-40itfNLYzqfig