-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathx-for-object.html
102 lines (101 loc) · 2.81 KB
/
x-for-object.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
---
title: "x-for with objects"
layout: example.njk
---
<div
x-data="{
todos: {
1: {
id: 1,
text: 'todo-1'
},
2: {
id: 2,
text: 'todo-2'
}
},
sections: Array.from(document.querySelectorAll('h3[id]')).map(e => ({ id: e.id, text: e.innerText })),
heading: location.hash
}"
x-init="heading && window.scrollTo({
top: $el.querySelector(heading).offsetTop
})"
class="md:w-2/3 mx-auto flex flex-col pb-8"
>
<div class="leading-tight mb-4">
<strong class="block">Table of contents</strong>
<ul class="list-inside pt-2 mb-4">
<template x-for="section in sections" :key="section.id">
<li class="list-disc w-full">
<a
class="text-blue-500 hover:text-blue-800 hover:underline"
:href="`#${section.id}`"
x-text="section.text"
></a>
</li>
</template>
</ul>
<p>
See the full post on
<a
class="text-blue-500 hover:text-blue-800 hover:underline"
href="https://codewithhugo.com/"
>@todo</a
>
</p>
</div>
<div>
<strong>x-data state:</strong>
<pre><code x-text="JSON.stringify({ todos }, null, 2)"></code></pre>
</div>
<div class="mb-8">
<h3 class="text-xl font-semibold text-gray-900" id="ids-only">
Only need the keys/ids - use <code>Object.keys</code>
</h3>
<ul>
<template x-for="id in Object.keys(todos)" :key="id">
<li>id: <span x-text="id"></span></li>
</template>
</ul>
</div>
<div class="mb-8">
<h3 class="text-xl font-semibold text-gray-900" id="ids-content-entries">
Need keys/ids and values - use <code>Object.entries</code>
</h3>
<select>
<template x-for="[id, value] in Object.entries(todos)" :key="id">
<option :value="id" x-text="value.text"></option>
</template>
</select>
</div>
<div class="mb-8">
<h3 class="text-xl font-semibold text-gray-900" id="ids-content-keys">
Need keys/ids and values - use <code>Object.keys</code> + lookup
</h3>
<select>
<template x-for="id in Object.keys(todos)" :key="id">
<option :value="id" x-text="todos[id].text"></option>
</template>
</select>
</div>
<div class="mb-8">
<h3 class="text-xl font-semibold text-gray-900" id="content-values">
Need only values - use <code>Object.values</code>
</h3>
<ul>
<template x-for="todo in Object.values(todos)" :key="todo">
<li x-text="todo.text"></li>
</template>
</ul>
</div>
<div>
<h3 class="text-xl font-semibold text-gray-900" id="content-keys">
Need values - use <code>Object.keys</code> + lookup
</h3>
<ul>
<template x-for="id in Object.keys(todos)" :key="id">
<li x-text="todos[id].text"></li>
</template>
</ul>
</div>
</div>