Reputation: 18482
I want to write a function that returns an array. The array contains objects, where some of them need to reuse a certain object (metadata
in this example). This object depends on a parameter of the function and repeating it would be a bit cumbersome.
I tried this:
local fn(name) = [
local metadata = { name: name };
{ metadata: metadata, value: "foo" },
{ metadata: metadata, value: "bar" },
];
fn("blub")
Unfortunately I get this error:
STATIC ERROR: example.jsonnet:4:17-24: Unknown variable: metadata
I would expect that metadata
is also available within the second item. Is there a way to solve this without repeating metadata
and without having the function return an object?
Upvotes: 2
Views: 2124
Reputation: 2991
When you have local foo = expr1; expr2
, foo
is defined only in expr2
. So in the example you provided metadata
is visible only in the first element of the array. And local is just an expression. You can use it anywhere in the code where an expression is expected, e.g. 42 + (local x = 17 - 3; x + 4)
. The local
in Jsonnet is an analog of let ... in ...
from Haskell/Ocaml etc.
The solution is to define metadata
for the whole array expression, like in the OP's answer.
Upvotes: 3