Get object of object value with variable in Pug?

1.8k Views Asked by At

I want to use the value of a variable to access an object in Pug.

elem : { Tuteur:{ Name:String, GivenName:String } }

Example:

let tmp = "Tuteur.Name",
    tmp_1 = "Tuteur.GivenName";

Code Pug:

p #{elem[tmp]};
p #{elem[tmp_1]};
1

There are 1 best solutions below

0
On

As this is not simple code, you're better off doing this in the route and not in the pug template. Pug templates only handle one-line expressions and this will require a multi-line function.

There is an example contained in the accepted Answer to this SO Question that shows how to do this in ten lines of code.

We use the Sugar Object.get utility function to do this in our application:

Sugar.Object.get(elem, "Tuteur.Name")

There are other JavaScript libraries that will do this, like underscore and lodash.

Finally, it's easier to define expressions like this instead of using interpolation:

p= elem.Tuteur.name