Add loop captures to capture struct

This commit is contained in:
jaina heartles 2022-11-16 00:18:14 -08:00
parent 61493dc797
commit c9d0090ab2
2 changed files with 26 additions and 3 deletions

View file

@ -39,12 +39,12 @@ fn executeStatement(writer: anytype, comptime stmt: Statement, args: anytype, ca
const iterable = deref(args, fields); const iterable = deref(args, fields);
const subtemplate = loop.subtemplate; const subtemplate = loop.subtemplate;
try writer.writeAll("capture on " ++ loop.capture ++ ": "); try writer.writeAll("capture on " ++ loop.capture ++ ": ");
for (iterable) |_| { for (iterable) |v| {
try executeTemplate( try executeTemplate(
writer, writer,
subtemplate, subtemplate,
args, args,
captures, addCapture(captures, loop.capture, v),
); );
} }
}, },
@ -74,6 +74,29 @@ fn deref(arg: anytype, comptime names: []const []const u8) Deref(@TypeOf(arg), n
return deref(@field(arg, names[0]), names[1..]); return deref(@field(arg, names[0]), names[1..]);
} }
fn AddCapture(comptime Root: type, comptime name: []const u8, comptime Val: type) type {
var fields = std.meta.fields(Root) ++ [_]std.builtin.Type.StructField{.{
.name = name,
.field_type = Val,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(Val),
}};
return @Type(.{ .Struct = .{
.layout = .Auto,
.fields = fields,
.decls = &.{},
.is_tuple = false,
} });
}
fn addCapture(root: anytype, comptime name: []const u8, val: anytype) AddCapture(@TypeOf(root), name, @TypeOf(val)) {
var result = std.mem.zeroInit(AddCapture(@TypeOf(root), name, @TypeOf(val)), root);
@field(result, name) = val;
return result;
}
const TemplateType = enum { const TemplateType = enum {
root, root,
subtemplate, subtemplate,

View file

@ -10,7 +10,7 @@
<section> <section>
{$bar} {$bar}
{#for .foo |$f|}a testing thing {#end_for} {#for .foo |$f|}a testing thing: {$f} {#end_for}
{{#for args.notes |$note, $i|}} {{#for args.notes |$note, $i|}}
<h3>Note no. {{$i}}</h3> <h3>Note no. {{$i}}</h3>
{{#template note_display ($note)}} {{#template note_display ($note)}}