fix: braced property access

This commit is contained in:
wyozi
2020-10-09 21:18:40 +08:00
committed by Jun Yang
parent a6126c3bea
commit 18a807ea2e
4 changed files with 24 additions and 2 deletions
+8
View File
@@ -207,6 +207,14 @@ export class Tokenizer {
const value = this.readQuoted() || this.readRange() const value = this.readQuoted() || this.readRange()
if (value) return value if (value) return value
if (this.peek() === '[') {
this.p++
const prop = this.readQuoted()
if (!prop) return
this.readTo(']')
return new PropertyAccessToken(prop, [], this.p)
}
const variable = this.readWord() const variable = this.readWord()
if (!variable.size()) return if (!variable.size()) return
+1 -1
View File
@@ -42,7 +42,7 @@ export class Expression {
export function evalToken (token: Token | undefined, ctx: Context): any { export function evalToken (token: Token | undefined, ctx: Context): any {
assert(ctx, () => 'unable to evaluate: context not defined') assert(ctx, () => 'unable to evaluate: context not defined')
if (TypeGuards.isPropertyAccessToken(token)) { if (TypeGuards.isPropertyAccessToken(token)) {
const variable = token.variable.getText() const variable = token.getVariableAsText()
const props: string[] = token.props.map(prop => evalToken(prop, ctx)) const props: string[] = token.props.map(prop => evalToken(prop, ctx))
return ctx.get([variable, ...props]) return ctx.get([variable, ...props])
} }
+10 -1
View File
@@ -2,13 +2,22 @@ import { Token } from './token'
import { WordToken } from './word-token' import { WordToken } from './word-token'
import { QuotedToken } from './quoted-token' import { QuotedToken } from './quoted-token'
import { TokenKind } from '../parser/token-kind' import { TokenKind } from '../parser/token-kind'
import { parseStringLiteral } from '../parser/parse-string-literal'
export class PropertyAccessToken extends Token { export class PropertyAccessToken extends Token {
constructor ( constructor (
public variable: WordToken, public variable: WordToken | QuotedToken,
public props: (WordToken | QuotedToken | PropertyAccessToken)[], public props: (WordToken | QuotedToken | PropertyAccessToken)[],
end: number end: number
) { ) {
super(TokenKind.PropertyAccess, variable.input, variable.begin, end, variable.file) super(TokenKind.PropertyAccess, variable.input, variable.begin, end, variable.file)
} }
getVariableAsText() {
if (this.variable instanceof WordToken) {
return this.variable.getText()
} else {
return parseStringLiteral(this.variable.getText())
}
}
} }
+5
View File
@@ -18,4 +18,9 @@ describe('Issues', function () {
const html = await engine.parseAndRender(template) const html = await engine.parseAndRender(template)
expect(html).to.equal('foo') expect(html).to.equal('foo')
}) })
it('#259 complex property access with braces is not supported', async () => {
const engine = new Liquid()
const html = engine.parseAndRenderSync('{{ ["complex key"] }}', { 'complex key': 'foo' })
expect(html).to.equal('foo')
})
}) })