If you are willing to incorporate some TypeScript logic, then this task can definitely be accomplished.
Before diving in: remember to enclose all tags within double curly braces. Instead of writing .string({field}}
, ensure it is written as .string({{field}}}
.
When it comes to interpolating a value with .uint32()
, the variable tag is what you need. Let's call it counter
:
.uint32({{counter}})
As a result, your complete template will appear like this:
encode(writer: _m0.Writer = _m0.Writer.create()) {
{{#fields}}
writer.uint32({{counter}}).string({{field}}}
{{/fields}}
}
The pressing question now is how to guarantee that counter
exists and assumes the correct value with each iteration of {{#fields}}...{{/fields}}
. One straightforward method is to prep the data you provide to the template so that every field
aligns with a corresponding counter
with the accurate value:
{
fields: [{
field: 'ab',
counter: 10,
}, {
field: 'cd',
counter: 18,
}, {
field: 'ef',
counter: 26,
}],
}
However, if you prefer an automatic computation method, lambdas can help (refer to the link provided for more details). To begin with, create a function that generates functions which produce the subsequent number in a series upon invocation:
function iterate(initialValue, increment) {
let value = initialValue;
return function() {
const oldValue = value;
value += increment;
return oldValue;
};
}
Now, introduce this function as the counter
in the data passed to the template:
{
fields: [{
field: 'ab',
}, {
field: 'cd',
}, {
field: 'ef',
}],
counter: iterate(10, 8),
}
Using either approach will yield the same outcome:
encode(writer: _m0.Writer = _m0.Writer.create()) {
writer.uint32(10).string(ab}
writer.uint32(18).string(cd}
writer.uint32(26).string(ef}
}
You can experiment with this setup in the Wontache playground by inserting the provided code into its load/store box.
{"data":{"text":"{\n fields: [{\n field: 'ab',\n }, {\n field: 'cd',\n }, {\n field: 'ef',\n }],\n counter: (function(initialValue, increment) {\n let value = initialValue;\n return function() {\n const oldValue = value;\n value += increment;\n return oldValue;\n };\n }(10, 8)),\n}"},"templates":[{"name":"encoding","text":"encode(writer: _m0.Writer = _m0.Writer.create()) {\n {{#fields}}\n writer.uint32({{counter}}).string({{field}}}\n \{{/fields}}\n}"}]}