DEV Community

Pallat Anchaleechamaikorn
Pallat Anchaleechamaikorn

Posted on

</> htmx handle array response

จากคราวก่อนที่เราสามารถรับ json response มาแสดงผลใน html ได้แล้ว แต่ถ้าเกิดว่า response นั้นส่งกลับมาเป็น array ล่ะ เราจะจัดการมันแบบไหนดี เรามาดูตัวอย่างกัน

index.html

<script src="https://unpkg.com/htmx.org@2.0.3"></script>
<script src="https://unpkg.com/htmx.org@1.9.12/dist/ext/json-enc.js"></script>
<script src="https://unpkg.com/htmx-ext-client-side-templates@2.0.0/client-side-templates.js"></script>
<script src="https://unpkg.com/mustache@latest"></script>

<div hx-ext="client-side-templates">
    <form hx-post="/api" hx-swap="innerHTML" hx-target="#content" hx-ext="json-enc" mustache-array-template="mytemplate">
        <div><textarea placeholder="Leave a comment here" name="message" id="message"></textarea></div>
        <div><input type="text" name="name" id="name" placeholder="name" required></div>
        <button type="submit">Submit</button>
    </form>

    <div id="content">replace here</div>

    <template id="mytemplate">
        {{#data}}
        <div>
            <p> {{message}} {{name}}</p>
        </div>
        {{/data}}
    </template>
</div>
Enter fullscreen mode Exit fullscreen mode

main.go

package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("./"))
    http.Handle("/", fs)

    http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        _, err := io.ReadAll(r.Body)
        if err != nil {
            log.Fatal(err)
        }
        r.Body.Close()

        json.NewEncoder(w).Encode([]map[string]string{
            {
                "message": "test message #1",
                "name":    "test name #1",
            },
            {
                "message": "test message #2",
                "name":    "test name #2",
            },
        })
    })

    http.ListenAndServe(":8910", nil)
}
Enter fullscreen mode Exit fullscreen mode

จากตัวอย่างนี้ เราแก้ให้ API คืน response ออกมาเป็น array 2 records
ส่วนที่ html เราใช้ htmx เหมือนตอนที่เรารับ json object ปกติเลย
สิ่งที่ต่างไปจากเดิมก็คือ mustache-template="mytemplate" เป็น mustache-array-template="mytemplate"

แล้วที่ template ให้ใส่ {{#data}} ครอบแล้วปิดด้วย {{/data}}

{{#data}}
  <!-- fields -->
{{/data}}
Enter fullscreen mode Exit fullscreen mode

นอกนั้นก็จัดรูปแบบไว้ มันจะ repeat ของใน array ไปจนกว่าจะหมด

ถึงตอนนี้ เราก็น่าจะใช้ htmx จัดการ request/response ในรูปแบบ json เบื้องต้นได้ค่อนข้างครอบคลุมแล้วนะครับ หวังว่าจะเป็นประโยชน์

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up