SendGrid Handlebars变量taskCount在greaterThan块内多次调用失效问题
问题成因
- SendGrid 封装的
greaterThan等自定义条件块助手存在作用域覆盖行为:当你进入{{#greaterThan 条件}}包裹的代码块时,块内的默认上下文会被替换为条件判断的布尔返回值(也就是此处的true),不再默认继承父级的全局数据上下文。 - 第一层
greaterThan判断时还处于全局上下文,所以可以正常读取到taskCount=5进入对应分支,但进入块内部后,直接调用taskCount相当于在布尔值true上查找同名属性,自然找不到返回空值,因此触发了insert标签的默认值1,嵌套的greaterThan taskCount 1也因为拿不到值判断不成立,没有输出(s)。
修复方案
把块内所有调用 taskCount 的地方改为回退到父级上下文,或者直接引用根上下文即可,两种写法都可以生效:
- 用
../回退父级上下文
{{#greaterThan taskCount 0}} Congrats on starting {{insert ../taskCount "default=1"}} task{{#greaterThan ../taskCount 1}} (s){{/greaterThan}} and taking the first small step. {{else}} You have not started a task yet. What are you waiting for? It has been {{DaysSinceJoined}} days since you joined on {{JoinedAt}}. You have missed {{DaysSinceJoined}} days where you could been making Small Steps towards the dreams of you better tomorrow. {{/greaterThan}}
- 用
@root直接引用根上下文
{{#greaterThan taskCount 0}} Congrats on starting {{insert @root.taskCount "default=1"}} task{{#greaterThan @root.taskCount 1}} (s){{/greaterThan}} and taking the first small step. {{else}} You have not started a task yet. What are you waiting for? It has been {{DaysSinceJoined}} days since you joined on {{JoinedAt}}. You have missed {{DaysSinceJoined}} days where you could been making Small Steps towards the dreams of you better tomorrow. {{/greaterThan}}
内容的提问来源于stack exchange,提问作者ChampChris
相关产品推荐
相关产品推荐

