Tap into Aurelia expression parser

The story is like this, as a front-end developer, I want to push more logic from backend so I can write less code.

To make my front-end neat and flexible, I ask my backend buddy to send me meta-data to control some behaviour of front-end view. We can either design a meta-data format rigid and complex to meet all our use cases, or we can design a light format with the help of something that can be “executed” in front-end.

Take a concrete example, let’s say backend wants to control a visibility of a page based on user has role3 or (role1 plus role2).

What about pass a function body in string as "function(user) { return ...}", then eval in front-end? That’s obviously bad.

What about pass a very readable expression string as "role3 || (role1 && role2)", then figure out how to safely “eval” it in front-end?

Well, Aurelia has an expression parser built-in. That is what it uses to understand those expressions you wrote in html template. It’s not JavaScript, it implemented a subset of JavaScript expression. Since it is not eval, it is safe.

To use it, it’s easier than you might expect. First inject Parser (get from ‘aurelia-framework’) into your component.

const expression = this.parser.parse("role3 || (role1 && role2)");
const granted = expression.evaluate({
  bindingContext: {role1: true, role2: true}
});

{bindingContext: obj} is the basic shape of a scope that expression will evaluate against.

See a working gistrun here:

I like Aurelia expression parser so much, I added my own spin (like es6 string interpolation) and use it to extreme. If you want to use the expression parser out of Aurelia, try

7 Likes