fix: elsif is not supported for unless, fixes #268

This commit is contained in:
harttle
2020-12-08 00:16:36 +08:00
parent a492d8e23d
commit 2bbf50171b
5 changed files with 47 additions and 8 deletions
+23 -4
View File
@@ -1,8 +1,9 @@
import { TopLevelToken, Template, Emitter, Expression, isFalsy, ParseStream, Context, TagImplOptions, Token, TagToken } from '../../types'
import { TopLevelToken, Template, Emitter, Expression, isTruthy, isFalsy, ParseStream, Context, TagImplOptions, TagToken } from '../../types'
export default {
parse: function (tagToken: TagToken, remainTokens: TopLevelToken[]) {
this.templates = []
this.branches = []
this.elseTemplates = []
let p
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
@@ -10,6 +11,12 @@ export default {
p = this.templates
this.cond = tagToken.args
})
.on('tag:elsif', (token: TagToken) => {
this.branches.push({
cond: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endunless', () => stream.stop())
.on('template', (tpl: Template) => p.push(tpl))
@@ -23,8 +30,20 @@ export default {
render: function * (ctx: Context, emitter: Emitter) {
const r = this.liquid.renderer
const cond = yield new Expression(this.cond, ctx.opts.lenientIf).value(ctx)
yield (isFalsy(cond, ctx)
? r.renderTemplates(this.templates, ctx, emitter)
: r.renderTemplates(this.elseTemplates, ctx, emitter))
if (isFalsy(cond, ctx)) {
yield r.renderTemplates(this.templates, ctx, emitter)
return
}
for (const branch of this.branches) {
const cond = yield new Expression(branch.cond, ctx.opts.lenientIf).value(ctx)
if (isTruthy(cond, ctx)) {
yield r.renderTemplates(branch.templates, ctx, emitter)
return
}
}
yield r.renderTemplates(this.elseTemplates, ctx, emitter)
}
} as TagImplOptions
+2 -3
View File
@@ -5,10 +5,9 @@ export function isTruthy (val: any, ctx: Context): boolean {
}
export function isFalsy (val: any, ctx: Context): boolean {
if(ctx.opts.jsTruthy) {
if (ctx.opts.jsTruthy) {
return !val
}
else {
} else {
return val === false || undefined === val || val === null
}
}