如何用Mustache模板编写TypeScript动态字段encode函数?
实现Mustache模板中递增8的uint32参数
可以实现这个需求,不过标准Mustache本身没有内置的循环索引或递增变量功能,需要通过以下两种方式解决:
方法一:预处理模板数据(标准Mustache兼容)
在将字段数据传给Mustache渲染前,先遍历字段数组,给每个字段添加对应的uint32值(初始10,每次递增8)。
比如用TypeScript预处理数据:
// 原始字段列表 const rawFields = ['xx', 'yy', 'zz']; // 预处理后的数据,给每个字段附加uint32数值 const templateContext = { fields: rawFields.map((fieldName, index) => ({ name: fieldName, uint32Val: 10 + index * 8 })) };
然后修改你的Mustache模板:
encode(writer: _m0.Writer = _m0.Writer.create()) { {{#fields}} writer.uint32({{uint32Val}}).string({{name}}); {{/fields}} }
这样渲染后就能得到你期望的代码,每个uint32()的参数会依次是10、18、26...
方法二:使用Mustache扩展(如Handlebars)
如果你的项目可以使用Handlebars(Mustache的超集),可以直接在模板中利用循环索引计算数值,无需预处理数据:
首先注册必要的辅助函数(如果环境不支持直接表达式计算):
Handlebars.registerHelper('calcUint32', (index) => 10 + index * 8);
然后编写模板:
encode(writer: _m0.Writer = _m0.Writer.create()) { {{#each fields}} writer.uint32({{calcUint32 @index}}).string({{this}}); {{/each}} }
部分Handlebars环境支持直接在模板中写算术表达式,也可以简化为:
encode(writer: _m0.Writer = _m0.Writer.create()) { {{#each fields}} writer.uint32({{10 + @index * 8}}).string({{this}}); {{/each}} }
内容的提问来源于stack exchange,提问作者AndyReifman
相关产品推荐
相关产品推荐

