Home > Blockchain >  AlpineJs: Loop in a a loop - How to use the first variable in the second loop?
AlpineJs: Loop in a a loop - How to use the first variable in the second loop?

Time:03-20

Basically I'm trying to generate a cricket dartboard with AlpineJs. It will be a table, with Players' name in the head, and scores for some determinating segments in the body.

So i declared some Alpine.datas :

Alpine.data('data', () => ({
            segments: ['20', '19', '18',],
            players: [
                {
                    name: 'Yann',
                    touched20: 0,
                    touched19: 0,
                    touched18: 0,
                },
                {
                    name: 'Morgan',
                    touched20: 0,
                    touched19: 0,
                    touched18: 0,
                },
            ],
        }));

So, foreach segment, i need a row, and foreach player a column. But I don't know how to use the first loop variable 'segment' to define the score of each player corresponding to this segment. In the first segment iteration, i have the variable segment = "20" and in the player loop i need to get "player.touched20", so in the second iteration i have segment = "19" and i need to get "player.touched19". Will be the same for various segments. My result with x-text="player.touched${segment}" returns a string but not the value of my alpine data.

So, there's my html :

<div x-data="data">
    <table>
        <thead>
            <tr>
                <th>///</th>
                <template x-for="player in players">
                    <th x-text="player.name"></th>
                </template>
            </tr>
        </thead>

        <tbody>
            <template x-for="segment in segments">
                <tr>
                    <td x-text="segment"></td>
                    <template x-for="player in players">
                        <td x-text="`player.touched${segment}`"></td>
                    </template>
                </tr>
            </template>
        </tbody>
    </table>
</div>

If anyone has an idea or a solution, it would be a very great help. Thanks

CodePudding user response:

Use the string literal syntax only for the dynamic attribute access part:

<td x-text="player[`touched${segment}`]"></td>
  • Related