使用mustache模板创建一个encode函数



我对小胡子很陌生,但我的基本谷歌似乎没有发现任何东西。我试图写一个模板在Typescript编码未知数量的字段。基本上它会像这样:

encode(writer: _m0.Writer = _m0.Writer.create()) {
writer.uint32(10).string(xx)
writer.uint32(18).string(xx)
writer.uint32(26).string(xx)
...
etc

我需要每次将uint32(xx)的值增加8。到目前为止,我的模板是

encode(writer: _m0.Writer = _m0.Writer.create()) {
{{#fields}}
writer.uint32().string({field}}
{{/fields}}
}

有可能做我想做的吗?

这是可以做到的,如果你接受一些逻辑需要在TypeScript中完成的话。

在我开始之前:您需要用双小胡子分隔所有标记。你不应该写.string({field}},而应该写.string({{field}}}

由于您在.uint32()的括号之间插入一个值,因此只有一个标记可以完成这项工作:变量标记。命名为counter:

.uint32({{counter}})
因此,在任何情况下,你的完整模板看起来像这样:
encode(writer: _m0.Writer = _m0.Writer.create()) {
{{#fields}}
writer.uint32({{counter}}).string({{field}}}
{{/fields}}
}

现在的问题是如何确保counter存在,并在每次迭代{{#fields}}...{{/fields}}时取正确的值。最直接的方法是准备提供给模板的数据,这样每个field都有一个相应的counter,并具有正确的值:

{
fields: [{
field: 'ab',
counter: 10,
}, {
field: 'cd',
counter: 18,
}, {
field: 'ef',
counter: 26,
}],
}

然而,您可能正在寻找一种自动计算数字的方法。在这种情况下,lambdas会支持您(单击该链接后需要向下滚动一点)。对于非常通用的解决方案,首先编写一个函数,该函数生成每次调用时返回序列中下一个数字的函数:

function iterate(initialValue, increment) {
let value = initialValue;
return function() {
const oldValue = value;
value += increment;
return oldValue;
};
}
现在,可以在传递给模板的数据中设置counter这样的函数:
{
fields: [{
field: 'ab',
}, {
field: 'cd',
}, {
field: 'ef',
}],
counter: iterate(10, 8),
}

无论使用哪一种方法,结果都是:

encode(writer: _m0.Writer = _m0.Writer.create()) {
writer.uint32(10).string(ab}
writer.uint32(18).string(cd}
writer.uint32(26).string(ef}
}

您可以通过将以下代码粘贴到wontacheplayground的加载/存储框中来尝试它。

{"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}"}]}

最新更新