posthtml / posthtml-expressions

Use variables, JS-like expressions, and even markup-powered logic in your HTML.
Other
123 stars 20 forks source link

Is it possible to pass arrays into include locals attribute? #130

Closed andrew-dotson closed 1 year ago

andrew-dotson commented 2 years ago

Sorry beginner coder here, this has been driving me nuts though. Is it possible to pass arrays directly in the tags locals attribute? I don't see any examples on how to do that...and then looping through the values. I know there are other ways to do it but was curious if you could pass it on the include itself.

thewebartisan7 commented 1 year ago

You should be able to pass any valid JSON objects, and your JSON object could have an item with an array.

{ "myArray": [1, 2, 3, 4] }

This should works, then you can access it using {{ myArray }} and loop over it using tag

andrew-dotson commented 1 year ago

You should be able to pass any valid JSON objects, and your JSON object could have an item with an array.

{ "myArray": [1, 2, 3, 4] }

This should works, then you can access it using {{ myArray }} and loop over it using tag

I guess my question is more how I can I do it in a include? Something like this?

<include src="components/list.html" locals='{list: ["item 1", "item 2"]}'></include> doesn't seem to work?

thewebartisan7 commented 1 year ago

<include src="components/list.html" locals='{list: ["item 1", "item 2"]}'></include> doesn't seem to work?

It's not working because it's not a valid JSON. JSON mandates that all keys must be strings.

This is valid:

{
  "list": [
    "item 1",
    "item 2"
  ]
}

So in your case is:

<include src="components/list.html" locals='{ "list": ["item 1", "item 2"] }'></include>
andrew-dotson commented 1 year ago

Thanks! That fixed it.