diff --git a/README.md b/README.md index c39ba61..919f72a 100644 --- a/README.md +++ b/README.md @@ -15,24 +15,33 @@ Syntax highlighters are currently community-sourced. Please get in touch if you ## Example -```html -// src/templates/example.zmpl +See [src/templates](src/templates) for more examples. +```html if (std.mem.eql(u8, "zmpl is simple", "zmpl" ++ " is " ++ "simple")) { + // Add comments using Zig syntax.
Email: {.user.email}
Token: {.auth.token}
+ + // Render a partial named `users/_mailto.zmpl`: +
{^users/mailto}
+ + <>Use fragment tags when you want to output content without a specific HTML tag + <#> - + Use multi-line raw text tags to bypass Zmpl syntax. + Some example code with curly braces {} etc. - <>Use fragment tags when you want to output content without a specific HTML tag + + Escape curly braces {{like this}} } ``` ```zig +const std = @import("std"); const zmpl = @import("zmpl"); -const manifest = @import("templates/zmpl.manifest.zig"); // Auto-generated by Zmpl. +const allocator = std.testing.allocator; +const manifest = @import("zmpl.manifest"); // Generated at build time test "readme example" { var data = zmpl.Data.init(allocator); @@ -48,14 +57,23 @@ test "readme example" { 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( - \\
Email: user@example.com
- \\
Token: abc123-456-def
- \\ - , output); + if (manifest.find("example")) |template| { + const output = try template.render(&data); + defer allocator.free(output); + + try std.testing.expectEqualStrings( + \\
Email: user@example.com
+ \\
Token: abc123-456-def
+ \\
user@example.com
+ \\ Use fragment tags when you want to output content without a specific HTML tag + \\ Use multi-line raw text tags to bypass Zmpl syntax. + \\ Some example code with curly braces {} etc. + \\ Escape curly braces {like this} + \\ + , output); + } else { + try std.testing.expect(false); + } } ``` diff --git a/build.zig b/build.zig index 9070814..50bd4f6 100644 --- a/build.zig +++ b/build.zig @@ -3,6 +3,7 @@ const builtin = @import("builtin"); pub const zmpl = @import("src/zmpl.zig"); pub const Data = zmpl.Data; +pub const Template = zmpl.Template; // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external @@ -36,16 +37,12 @@ pub fn build(b: *std.Build) !void { "zmpl_templates_path", "Directory to search for .zmpl templates.", ) orelse try std.fs.path.join(b.allocator, &[_][]const u8{ "src", "templates" }); - const manifest_path = b.option( - []const u8, - "zmpl_manifest_path", - "Zmpl auto-generated manifest path.", - ) orelse try std.fs.path.join(b.allocator, &[_][]const u8{ templates_path, "zmpl.manifest.zig" }); - try zmpl.init(b, lib, .{ - .manifest_path = manifest_path, - .templates_path = templates_path, - }); + const ZmplBuild = @import("src/zmpl/Build.zig"); + var zmpl_build = ZmplBuild.init(b, lib, templates_path); + const manifest_module = try zmpl_build.compile(Template); + + zmpl_module.addImport("zmpl.manifest", manifest_module); // This declares intent for the library to be installed into the standard // location when the user invokes the "install" step (the default step when @@ -70,6 +67,7 @@ pub fn build(b: *std.Build) !void { }); main_tests.root_module.addImport("zmpl", zmpl_module); + main_tests.root_module.addImport("zmpl.manifest", manifest_module); const run_main_tests = b.addRunArtifact(main_tests); // This creates a build step. It will be visible in the `zig build --help` menu, diff --git a/src/templates/_example_partial.zmpl b/src/templates/_example_partial.zmpl new file mode 100644 index 0000000..bae1ba9 --- /dev/null +++ b/src/templates/_example_partial.zmpl @@ -0,0 +1 @@ +An example partial diff --git a/src/templates/example.zmpl b/src/templates/example.zmpl index e1614bc..1d690f3 100644 --- a/src/templates/example.zmpl +++ b/src/templates/example.zmpl @@ -1,10 +1,17 @@ if (std.mem.eql(u8, "zmpl is simple", "zmpl" ++ " is " ++ "simple")) { + // Add comments using Zig syntax.
Email: {.user.email}
Token: {.auth.token}
+ + // Render a partial named `users/_mailto.zmpl`: +
{^users/mailto}
+ + <>Use fragment tags when you want to output content without a specific HTML tag + <#> - + Use multi-line raw text tags to bypass Zmpl syntax. + Some example code with curly braces {} etc. - <>Use fragment tags when you want to output content without a specific HTML tag + + Escape curly braces {{like this}} } diff --git a/src/templates/example_with_[slug].zmpl b/src/templates/example_with_[slug].zmpl deleted file mode 100644 index b1e5887..0000000 --- a/src/templates/example_with_[slug].zmpl +++ /dev/null @@ -1 +0,0 @@ -
A template with a slug
diff --git a/src/templates/example_with_escaped_curly_braces.zmpl b/src/templates/example_with_escaped_curly_braces.zmpl new file mode 100644 index 0000000..dcd6568 --- /dev/null +++ b/src/templates/example_with_escaped_curly_braces.zmpl @@ -0,0 +1,3 @@ +
+ some escaped curly braces: {{foo}} +
diff --git a/src/templates/example_with_fragment_tag.zmpl b/src/templates/example_with_fragment_tag.zmpl index d36fdb5..4a30ef9 100644 --- a/src/templates/example_with_fragment_tag.zmpl +++ b/src/templates/example_with_fragment_tag.zmpl @@ -1,7 +1,3 @@
-

-  <>pub fn main() void \{
-  <>  std.debug.print("Hello, World!\\n", .\{});
-  <>}
-  
+ <>some text in a fragment
diff --git a/src/templates/example_with_partial.zmpl b/src/templates/example_with_partial.zmpl new file mode 100644 index 0000000..8786f56 --- /dev/null +++ b/src/templates/example_with_partial.zmpl @@ -0,0 +1,2 @@ +
This is an example with a partial
+
{^example_partial}
diff --git a/src/templates/users/_mailto.zmpl b/src/templates/users/_mailto.zmpl new file mode 100644 index 0000000..f7b03b2 --- /dev/null +++ b/src/templates/users/_mailto.zmpl @@ -0,0 +1 @@ +{.user.email} diff --git a/src/templates/zmpl.manifest.zig b/src/templates/zmpl.manifest.zig index d4fc537..63a1ef1 100644 --- a/src/templates/zmpl.manifest.zig +++ b/src/templates/zmpl.manifest.zig @@ -3,6 +3,7 @@ // This file should _not_ be stored in version control. pub const templates = struct { pub const example = @import(".example.zmpl.compiled.zig"); + pub const example_with_partial = @import(".example_with_partial.zmpl.compiled.zig"); pub const example_with_array_data_lookup = @import(".example_with_array_data_lookup.zmpl.compiled.zig"); pub const example_with_multi_line_fragment_tag = @import(".example_with_multi_line_fragment_tag.zmpl.compiled.zig"); pub const example_with_root_array = @import(".example_with_root_array.zmpl.compiled.zig"); @@ -13,6 +14,7 @@ pub const templates = struct { pub const example_with_fragment_tag = @import(".example_with_fragment_tag.zmpl.compiled.zig"); pub const example_with_string_literal = @import(".example_with_string_literal.zmpl.compiled.zig"); pub const example_with_if_statement = @import(".example_with_if_statement.zmpl.compiled.zig"); + pub const _example_partial = @import("._example_partial.zmpl.compiled.zig"); pub const example_with_slug = @import(".example_with_[slug].zmpl.compiled.zig"); pub const example_with_local_variable_reference = @import(".example_with_local_variable_reference.zmpl.compiled.zig"); pub const example_with_quotes = @import(".example_with_quotes.zmpl.compiled.zig"); diff --git a/src/tests.zig b/src/tests.zig index 9792dbb..d02b6bd 100644 --- a/src/tests.zig +++ b/src/tests.zig @@ -1,7 +1,7 @@ const std = @import("std"); const zmpl = @import("zmpl"); const allocator = std.testing.allocator; -const manifest = @import("templates/zmpl.manifest.zig"); +const manifest = @import("zmpl.manifest"); // Generated at build time test "readme example" { var data = zmpl.Data.init(allocator); @@ -17,18 +17,23 @@ test "readme example" { 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( - \\
Email: user@example.com
- \\
Token: abc123-456-def
- \\ - \\ Use fragment tags when you want to output content without a specific HTML tag - \\ - , output); + if (manifest.find("example")) |template| { + const output = try template.render(&data); + defer allocator.free(output); + + try std.testing.expectEqualStrings( + \\
Email: user@example.com
+ \\
Token: abc123-456-def
+ \\
user@example.com
+ \\ Use fragment tags when you want to output content without a specific HTML tag + \\ Use multi-line raw text tags to bypass Zmpl syntax. + \\ Some example code with curly braces {} etc. + \\ Escape curly braces {like this} + \\ + , output); + } else { + try std.testing.expect(false); + } } test "template with if statement" { @@ -38,7 +43,8 @@ test "template with if statement" { var object = try data.object(); try object.put("foo", data.string("bar")); - const output = try manifest.templates.example_with_if_statement.render(&data); + const template = manifest.find("example_with_if_statement"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hi!
\n", output); @@ -48,7 +54,8 @@ test "template with quotes" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_quotes.render(&data); + const template = manifest.find("example_with_quotes"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
\"Hello!\"
\n", output); @@ -63,7 +70,8 @@ test "template with nested data lookup" { try nested_object.put("bar", data.integer(10)); try object.put("foo", nested_object); - const output = try manifest.templates.example_with_nested_data_lookup.render(&data); + const template = manifest.find("example_with_nested_data_lookup"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hello 10!
\n", output); @@ -78,7 +86,8 @@ test "template with array data lookup" { try nested_array.append(data.string("nested array value")); try object.put("foo", nested_array); - const output = try manifest.templates.example_with_array_data_lookup.render(&data); + const template = manifest.find("example_with_array_data_lookup"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hello nested array value!
\n", output); @@ -91,7 +100,8 @@ test "template with root array" { var array = try data.array(); try array.append(data.string("root array value")); - const output = try manifest.templates.example_with_root_array.render(&data); + const template = manifest.find("example_with_root_array"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hello root array value!
\n", output); @@ -110,7 +120,8 @@ test "template with deep nesting" { try nested_object.put("bar", double_nested_object); try object.put("foo", nested_object); - const output = try manifest.templates.example_with_deep_nesting.render(&data); + const template = manifest.find("example_with_deep_nesting"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hello :))
\n", output); @@ -126,7 +137,8 @@ test "template with iteration" { try array.append(data.string("hooray")); try object.put("foo", array); - const output = try manifest.templates.example_with_iteration.render(&data); + const template = manifest.find("example_with_iteration"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings(" yay\n hooray\n", output); @@ -136,27 +148,19 @@ test "template with local variable reference" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_local_variable_reference.render(&data); + const template = manifest.find("example_with_local_variable_reference"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("
Hello there!
\n", output); } -test "template with [slug]" { - var data = zmpl.Data.init(allocator); - defer data.deinit(); - - const output = try manifest.templates.example_with_slug.render(&data); - defer allocator.free(output); - - try std.testing.expectEqualStrings("
A template with a slug
\n", output); -} - test "template with string literal" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_string_literal.render(&data); + const template = manifest.find("example_with_string_literal"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings( @@ -171,7 +175,8 @@ test "template with Zig literal" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_zig_literal.render(&data); + const template = manifest.find("example_with_zig_literal"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings("false\n", output); @@ -187,7 +192,8 @@ test "template with complex content" { try array.append(data.string("howdy")); try array.append(data.string("hiya")); try array.append(data.string("good day")); - const output = try manifest.templates.example_with_complex_content.render(&data); + const template = manifest.find("example_with_complex_content"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings(output, @@ -228,16 +234,13 @@ test "template with fragment tag" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_fragment_tag.render(&data); + const template = manifest.find("example_with_fragment_tag"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings( \\
- \\

-        \\    pub fn main() void {
-        \\      std.debug.print("Hello, World!\n", .{});
-        \\    }
-        \\  
+ \\ some text in a fragment \\
\\ , output); @@ -247,7 +250,8 @@ test "template with multi-line fragment tag" { var data = zmpl.Data.init(allocator); defer data.deinit(); - const output = try manifest.templates.example_with_multi_line_fragment_tag.render(&data); + const template = manifest.find("example_with_multi_line_fragment_tag"); + const output = try template.?.render(&data); defer allocator.free(output); try std.testing.expectEqualStrings( @@ -275,6 +279,38 @@ test "template with multi-line fragment tag" { , output); } +test "template with escaped curly braces" { + var data = zmpl.Data.init(allocator); + defer data.deinit(); + + const template = manifest.find("example_with_escaped_curly_braces"); + const output = try template.?.render(&data); + defer allocator.free(output); + + try std.testing.expectEqualStrings( + \\
+ \\ some escaped curly braces: {foo} + \\
+ \\ + , output); +} + +test "template with partial" { + var data = zmpl.Data.init(allocator); + defer data.deinit(); + + const template = manifest.find("example_with_partial"); + const output = try template.?.render(&data); + defer allocator.free(output); + + const expected = + \\
This is an example with a partial
+ \\
An example partial
+ \\ + ; + try std.testing.expectEqualStrings(expected, output); +} + test "toJson" { var data = zmpl.Data.init(allocator); defer data.deinit(); diff --git a/src/zmpl.zig b/src/zmpl.zig index 7fdc874..d0688ee 100644 --- a/src/zmpl.zig +++ b/src/zmpl.zig @@ -12,12 +12,10 @@ pub const Template = @import("./zmpl/Template.zig"); pub const Data = @import("./zmpl/Data.zig"); pub const ZmplBuild = @import("./zmpl/Build.zig"); +pub const manifest = @import("zmpl.manifest"); + pub const InitOptions = struct { templates_path: []const u8 = "src/templates", - manifest_path: []const u8 = "src/templates/zmpl.manifest.zig", }; -pub fn init(build: *std.Build, lib: *std.Build.Step.Compile, options: InitOptions) !void { - var zmpl_build = ZmplBuild.init(build, lib, options.manifest_path, options.templates_path); - try zmpl_build.compile(); -} +pub const find = manifest.find; diff --git a/src/zmpl/Build.zig b/src/zmpl/Build.zig index 7857b27..5f2ec20 100644 --- a/src/zmpl/Build.zig +++ b/src/zmpl/Build.zig @@ -1,120 +1,139 @@ const std = @import("std"); const builtin = @import("builtin"); -const zmpl = @import("../zmpl.zig"); build: *std.Build, -step: *std.Build.Step.Compile, -manifest_path: []const u8, +lib: *std.Build.Step.Compile, templates_path: []const u8, const Self = @This(); const TemplateDef = struct { - path: []const u8, - relpath: []const u8, + lazy_path: std.Build.LazyPath, name: []const u8, + module_name: []const u8, }; pub fn init( build: *std.Build, - step: *std.Build.Step.Compile, - manifest_path: []const u8, + lib: *std.Build.Step.Compile, templates_path: []const u8, ) Self { return .{ .build = build, - .step = step, - .manifest_path = manifest_path, + .lib = lib, .templates_path = templates_path, }; } -pub fn compile(self: *Self) !void { - var templates = std.ArrayList(TemplateDef).init(self.build.allocator); +pub fn compile(self: *Self, comptime Template: type) !*std.Build.Module { + var template_defs = std.ArrayList(TemplateDef).init(self.build.allocator); - self.compileTemplates(&templates) catch |err| { + var write_files = self.build.addWriteFiles(); + + self.compileTemplates(&template_defs, Template) catch |err| { switch (err) { error.TemplateDirectoryNotFound => { std.debug.print( "[zmpl] Template directory `{s}` not found, skipping compilation.\n", .{self.templates_path}, ); - return; }, else => return err, } }; - var dir = std.fs.cwd(); - var file = try dir.createFile(self.manifest_path, .{ .truncate = true }); - try file.writeAll( + var buf = std.ArrayList(u8).init(self.build.allocator); + const writer = buf.writer(); + defer buf.deinit(); + + try writer.writeAll( \\// Zmpl template manifest. - \\// This file is automatically generated at build time. Manual edits will be discarded. - \\// This file should _not_ be stored in version control. - \\pub const templates = struct { + \\// This file is automatically generated at build time and should not be manually modified. + \\ + \\const std = @import("std"); + \\const zmpl = @import("zmpl"); + \\ + \\pub const Template = struct { + \\ name: []const u8, + \\ render: *const fn(*zmpl.Data) anyerror![]const u8, + \\}; + \\ + \\pub fn find(name: []const u8) ?Template { + \\ for (templates) |template| { + \\ if (std.mem.eql(u8, name, template.name)) return template; + \\ } else { + \\ return null; + \\ } + \\} + \\pub const templates = [_]Template{ \\ ); - for (templates.items) |template| { - const module = self.build.createModule(.{ .root_source_file = .{ .path = template.path } }); - self.step.root_module.addImport(template.name, module); - try file.writeAll(try std.fmt.allocPrint( + for (template_defs.items) |template_def| { + try writer.writeAll(try std.fmt.allocPrint( self.build.allocator, - " pub const {s} = @import(\"{s}\");\n", + \\ .{{ .name = "{s}", .render = @import("{s}").render }}, + \\ + , .{ - template.name, - template.relpath, + template_def.name, + template_def.module_name, }, )); } - try file.writeAll("};\n"); - file.close(); + try writer.writeAll("};\n"); + const lazy_path = write_files.add("zmpl.manifest.zig", buf.items); + + const manifest_module = self.build.addModule("zmpl.manifest", .{ .root_source_file = lazy_path }); + manifest_module.addImport("zmpl", self.build.modules.get("zmpl").?); + + for (template_defs.items) |template_def| { + const template_module = self.build.createModule(.{ .root_source_file = template_def.lazy_path }); + template_module.addImport("zmpl", self.build.modules.get("zmpl").?); + manifest_module.addImport(template_def.module_name, template_module); + } + self.lib.root_module.addImport("zmpl.manifest", manifest_module); + + return manifest_module; } -fn compileTemplates(self: *Self, array: *std.ArrayList(TemplateDef)) !void { +fn compileTemplates( + self: *Self, + array: *std.ArrayList(TemplateDef), + comptime Template: type, +) !void { const paths = try self.findTemplates(); - const dir = try std.fs.cwd().openDir(self.templates_path, .{}); + var dir = try std.fs.cwd().openDir(self.templates_path, .{}); + defer dir.close(); + for (paths.items) |path| { + var write_files = self.build.addWriteFiles(); + std.debug.print("[zmpl] Compiling template: {s}\n", .{path}); const output_path = try std.fs.path.join( self.build.allocator, - &[_][]const u8{ - std.fs.path.dirname(path) orelse "", - try std.mem.concat(self.build.allocator, u8, &[_][]const u8{ - ".", - std.fs.path.basename(path), - ".compiled.zig", - }), - }, + &[_][]const u8{ "templates", path }, ); + var file = try dir.openFile(path, .{}); const size = (try file.stat()).size; const buffer = try self.build.allocator.alloc(u8, size); const content = try dir.readFile(path, buffer); - var template = zmpl.Template.init(self.build.allocator, path, content); + var template = Template.init(self.build.allocator, path, content); const output = try template.compile(); - const output_file = try dir.createFile(output_path, .{ .truncate = true }); - try output_file.writeAll(output); - output_file.close(); - var template_def: TemplateDef = .{ - .path = try dir.realpathAlloc(self.build.allocator, output_path), - .relpath = output_path, + const lazy_path = write_files.add(output_path, output); + const template_def: TemplateDef = .{ + .lazy_path = lazy_path, .name = try template.identifier(), + .module_name = output_path, }; - if (builtin.os.tag == .windows) { - const windows_replacement_buffer = try self.build.allocator.alloc(u8, std.mem.replacementSize(u8, output_path, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix)); - _ = std.mem.replace(u8, output_path, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix, windows_replacement_buffer); - template_def.relpath = try self.build.allocator.dupe(u8, windows_replacement_buffer); - } try array.append(template_def); - - std.debug.print("[zmpl] Compiled template: {s}\n", .{path}); } } fn findTemplates(self: *Self) !std.ArrayList([]const u8) { var array = std.ArrayList([]const u8).init(self.build.allocator); - const dir = std.fs.cwd().openDir(self.templates_path, .{ .iterate = true }) catch |err| { + var dir = std.fs.cwd().openDir(self.templates_path, .{ .iterate = true }) catch |err| { switch (err) { error.FileNotFound => return error.TemplateDirectoryNotFound, else => return err, @@ -123,11 +142,10 @@ fn findTemplates(self: *Self) !std.ArrayList([]const u8) { var walker = try dir.walk(self.build.allocator); defer walker.deinit(); + while (try walker.next()) |entry| { if (entry.kind != .file) continue; const extension = std.fs.path.extension(entry.path); - const basename = std.fs.path.basename(entry.path); - if (std.mem.startsWith(u8, basename, ".")) continue; if (!std.mem.eql(u8, extension, ".zmpl")) continue; try array.append(try self.build.allocator.dupe(u8, entry.path)); } diff --git a/src/zmpl/Data.zig b/src/zmpl/Data.zig index ffbf4ca..f5d26bb 100644 --- a/src/zmpl/Data.zig +++ b/src/zmpl/Data.zig @@ -33,6 +33,7 @@ /// data tree (for Zmpl templates, use the `{.nested_object.key}` syntax to do this /// automatically. const std = @import("std"); +const manifest = @import("zmpl.manifest"); /// Output stream for writing values into a rendered template. pub const Writer = std.ArrayList(u8).Writer; @@ -47,6 +48,7 @@ output_buf: std.ArrayList(u8), output_writer: ?std.ArrayList(u8).Writer = null, value: ?*Value = null, Null: Value = .{ .Null = NullType{} }, +partial: bool = false, /// Creates a new `Data` instance which can then be used to store any tree of `Value`. pub fn init(allocator: std.mem.Allocator) Self { @@ -67,6 +69,31 @@ pub fn deinit(self: *Self) void { self.json_buf.deinit(); } +/// Render a partial template. Do not invoke directly, use `{^partial_name}` syntax instead. +pub fn renderPartial(self: *Self, name: []const u8) !void { + if (manifest.find(name)) |template| { + // Partials return an empty string as they share the same writer as parent template. + self.partial = true; + errdefer self.partial = false; + _ = try template.render(self); + self.partial = false; + } else { + return error.ZmplPartialNotFound; + } +} + +/// Chomps output buffer. Used for partials to allow user to add an explicit blank line at the +/// end of a template if needed, otherwise `
{^partial_name}
` should not output a +/// newline. +pub fn chompOutputBuffer(self: *Self) void { + if (std.mem.endsWith(u8, self.output_buf.items, "\r\n")) { + _ = self.output_buf.pop(); + _ = self.output_buf.pop(); + } else if (std.mem.endsWith(u8, self.output_buf.items, "\n")) { + _ = self.output_buf.pop(); + } +} + pub fn eql(self: *const Self, other: *const Self) bool { if (self.value != null and other.value != null) { return self.value.?.eql(other.value.?); diff --git a/src/zmpl/Template.zig b/src/zmpl/Template.zig index 3dd7c16..2cb4369 100644 --- a/src/zmpl/Template.zig +++ b/src/zmpl/Template.zig @@ -6,7 +6,7 @@ const Self = @This(); allocator: std.mem.Allocator, content: []const u8, -name: []const u8, +path: []const u8, buffer: std.ArrayList([]const u8), const MarkupLine = struct { @@ -17,6 +17,7 @@ const MarkupLine = struct { open: bool = false, escape: bool = false, decl: bool = false, + partial: bool = false, pub fn init(allocator: std.mem.Allocator, line: []const u8) MarkupLine { return .{ @@ -27,9 +28,18 @@ const MarkupLine = struct { }; } + // TODO: For now we somehow get away with a stackless parser by relying on lookahead but this + // is limiting and fragile. Build a proper syntax grammar and AST. pub fn compile(self: *MarkupLine) ![]const u8 { - for (self.line, 0..) |byte, index| { - _ = index; + var position: isize = -1; + + for (self.line) |_| { + const index: usize = @intCast(position + 1); + if (index >= self.line.len) break; + position += 1; + + const byte = self.line[index]; + if (byte == '\r') continue; if (byte == '\\' and !self.escape) { @@ -49,6 +59,11 @@ const MarkupLine = struct { continue; } + if (byte == '^' and self.open and self.reference_buffer.items.len == 0) { + self.partial = true; + continue; + } + if (byte == '"' and !self.open) { try self.buffer.append('\\'); try self.buffer.append('"'); @@ -67,12 +82,24 @@ const MarkupLine = struct { continue; } - if (byte == '{' and !self.escape) { + if (byte == '{' and lookAhead(self.line[index..], "{{")) { + position += 1; + try self.buffer.append('{'); + continue; + } + + if (byte == '}' and lookAhead(self.line[index..], "}}")) { + position += 1; + try self.buffer.append('}'); + continue; + } + + if (byte == '{') { self.openReference(); continue; } - if (byte == '}' and self.open) { + if (byte == '}') { try self.closeReference(); continue; } @@ -119,6 +146,8 @@ const MarkupLine = struct { fn compileReference(self: *MarkupLine) ![]const u8 { if (self.decl) { return try self.compileDeclReference(); + } else if (self.partial) { + return try self.compilePartial(); } else if (std.mem.startsWith(u8, self.reference_buffer.items, ".")) { return try self.compileDataReference(); } else if (std.mem.indexOfAny(u8, self.reference_buffer.items, " \"+-/*{}!?()")) |_| { @@ -128,6 +157,21 @@ const MarkupLine = struct { } } + // Convert `foo/bar/baz` into `_foo_bar_baz` to match template name. + fn compilePartial(self: *MarkupLine) ![]const u8 { + self.partial = false; + if (self.reference_buffer.items.len == 0) return error.ZmplPartialNameError; + + std.mem.replaceScalar(u8, self.reference_buffer.items, '/', '_'); + + const template = + \\ + \\try zmpl.renderPartial("_{s}"); + \\ + ; + return try std.fmt.allocPrint(self.allocator, template, .{self.reference_buffer.items}); + } + fn compileDataReference(self: *MarkupLine) ![]const u8 { return std.mem.concat(self.allocator, u8, &[_][]const u8{ \\try zmpl.write(try zmpl.getValueString(" @@ -196,29 +240,63 @@ const MarkupLine = struct { } }; -pub fn init(allocator: std.mem.Allocator, name: []const u8, content: []const u8) Self { +pub fn init(allocator: std.mem.Allocator, path: []const u8, content: []const u8) Self { return .{ .allocator = allocator, - .name = name, + .path = path, .content = content, .buffer = std.ArrayList([]const u8).init(allocator), }; } pub fn identifier(self: *Self) ![]const u8 { - var sanitized_array = std.ArrayList(u8).init(self.allocator); - for (self.name, 0..) |char, index| { - if (std.mem.indexOfAny(u8, &[_]u8{char}, "abcdefghijklmnopqrstuvwxyz")) |_| { - try sanitized_array.append(char); - } else if (index == 0) { - try sanitized_array.append('_'); - } else if (index < self.name.len - 1 and sanitized_array.items[sanitized_array.items.len - 1] != '_') { - try sanitized_array.append('_'); + var segments = std.ArrayList([]const u8).init(self.allocator); + defer segments.deinit(); + + var it = std.mem.splitScalar(u8, self.path, std.fs.path.sep); + while (it.next()) |segment| { + try segments.append(segment); + } + const basename = segments.pop(); + defer self.allocator.free(basename); + + var partial = false; + + if (basename.len > 0 and std.mem.startsWith(u8, basename, "_")) { + partial = true; + try segments.append(basename[1..]); + } else { + try segments.append(basename); + } + + const name = try std.mem.join(self.allocator, "_", segments.items); + defer self.allocator.free(name); + + var valid_name_array = std.ArrayList(u8).init(self.allocator); + defer valid_name_array.deinit(); + + const valid_anywhere = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY_"; + const valid_after_zero = valid_anywhere ++ "0123456789"; + const substitutable = "."; + + const extension = std.fs.path.extension(self.path); + const base_path = name[0 .. name.len - extension.len]; + + for (base_path, 0..) |char, index| { + if (index == 0 and partial) try valid_name_array.append('_'); + if (index == 0 and std.mem.containsAtLeast(u8, valid_anywhere, 1, &[_]u8{char})) { + try valid_name_array.append(char); + } else if (index > 0 and std.mem.containsAtLeast(u8, valid_after_zero, 1, &[_]u8{char})) { + try valid_name_array.append(char); + } else if (std.mem.containsAtLeast(u8, substitutable, 1, &[_]u8{char})) { + try valid_name_array.append('_'); + } else { + std.debug.print("[zmpl] Invalid filename (must be '[a-zA-Z0-9_]+.zmpl'): {s}\n", .{self.path}); + return error.ZmplInvalidFileNameError; } } - const extension = std.fs.path.extension(self.name); - return sanitized_array.items[0 .. sanitized_array.items.len - extension.len]; + return try self.allocator.dupe(u8, valid_name_array.items); } pub fn compile(self: *Self) ![]const u8 { @@ -226,6 +304,7 @@ pub fn compile(self: *Self) ![]const u8 { try self.buffer.append( \\const std = @import("std"); \\const __zmpl = @import("zmpl"); + \\ \\pub fn render(zmpl: *__zmpl.Data) anyerror![]const u8 { \\ const allocator = zmpl.getAllocator(); \\ _ = try allocator.alloc(u8, 0); // no-op to avoid unused local constant @@ -247,12 +326,12 @@ pub fn compile(self: *Self) ![]const u8 { const index = std.mem.indexOfNone(u8, line, " "); if (index) |i| { - if (try self.parseFragment(line[i..])) |fragment| { - // Preserve indentation, replace "<>" with " " + if (parseFragment(line[i..])) |fragment| { var buf = std.ArrayList(u8).init(self.allocator); defer buf.deinit(); const writer = buf.writer(); - for (0..i + "<>".len) |_| try writer.writeByte(' '); + // Preserve indentation + for (0..i) |_| try writer.writeByte(' '); try writer.writeAll(fragment); try self.buffer.append(try self.compileMarkupLine(buf.items)); continue; @@ -274,7 +353,10 @@ pub fn compile(self: *Self) ![]const u8 { } } - try self.buffer.append("return zmpl._allocator.dupe(u8, zmpl.output_buf.items);"); + try self.buffer.append( + \\if (zmpl.partial) zmpl.chompOutputBuffer(); + \\return zmpl._allocator.dupe(u8, if (zmpl.partial) "" else zmpl.output_buf.items); + ); try self.buffer.append("}"); return try std.mem.join(self.allocator, "\n", self.buffer.items); @@ -282,11 +364,11 @@ pub fn compile(self: *Self) ![]const u8 { // TODO: Multi-line fragments - curently just assumes there might be a `` on the same line and // removes it if present. -fn parseFragment(self: *Self, string: []const u8) !?[]const u8 { +fn parseFragment(string: []const u8) ?[]const u8 { const tag = "<>"; if (std.mem.startsWith(u8, string, tag)) { - const replaced = try std.mem.replaceOwned(u8, self.allocator, string, "", ""); - if (replaced.len > tag.len) return replaced[tag.len..] else return ""; + const close_index = std.mem.lastIndexOf(u8, string, "") orelse string.len - 1; + return string[tag.len..close_index]; } return null; }