Wakan Tanka
Wakan Tanka

Reputation: 8052

Addressing parent elemens from nested (children)

I have following jsonnet.

{
        local property = "global variable",

        property: "global property",
        bar: self.property,   // global property
        baz: property,        // global variable

        nested: {
            local property = "local variable",

            property: "local property",
            bar: self.property,       // local property
            baz: property,            // local variable

            // Q1:
            // Can I get the property of parent from here? In my case:
            // property: "global property"
            // I want to use some kind of relative addressing, from child to parent not other way like:
            // $.property
            // I've tried:
            // super.property
            // but got errors

            // Q2:
            // Can I get the name of the key in which this block is wrapped? In my case:
            // "nested"
        }
}

My goal is to access parent from child. Questions are in comments for better context understanding. Thanks

Upvotes: 2

Views: 1339

Answers (1)

jjo
jjo

Reputation: 3020

Note that super is used for object ~inheritance (i.e. when you extend a base object to e.g. override some fields, see https://jsonnet.org/learning/tutorial.html#oo ).

The trick is to plug a local variable pointing to the object's self you want to refer to:

{
        local property = "global variable",

        property: "global property",
        bar: self.property,   // global property
        baz: property,        // global variable

        // "Plug" a local variable pointing here
        local this = self,

        nested: {
            local property = "local variable",

            property: "local property",
            bar: self.property,       // local property
            baz: property,            // local variable

            // Use variable set at container obj
            glo1: this.property,
            // In this particular case, can also use '$' to refer to the root obj
            glo2: $.property,
        }
}

Upvotes: 3

Related Questions