Reputation: 746
I have a JSON variable which contains attributes in the following manner:
// JSON variable defining attributes for elements to be created
let myElements = [
{
attr1: "myAttr1",
attr2: "myAttr2",
},
{
attr1: "myAttr4",
attr2: "myAttr5",
}
];
I want to render HTML elements based on the attributes defined in the JSON variable using the each block as shown below:
<-- Svelte Code -->
{#each myElements as myElement}
<div {myElement.attr1} {myElement.attr2}>
</div>
{/each}
So that they will be rendered in this way:
<-- Desired Resultant HTML -->
<div attr1="myAttr1" attr="myAttr2"></div>
<div attr1="myAttr4" attr2="myAttr5"></div>
However, svelte shows an "Expected a }" error when I refer to attributes like {myElement.attr1}
in an HTML tag. Is it possible to use the shorthand attributes in this way?
Upvotes: 0
Views: 332
Reputation: 2261
you could use deconstruction
<script>
let things = [
{attr1:'a',attr2:'b'},
{attr1:'ace',attr2:'bdd'},
{attr1:'as',attr2:'bsd'},
]
</script>
{#each things as {attr1, attr2}}
<div {attr1} {attr2}>{attr1}</div>
{/each}
Upvotes: 1