搜尋
首頁後端開發GolangGolang htmx Tailwind CSS:建立響應式 Web 應用程式

背景

在當今的 Web 開發領域,JavaScript 長期以來一直是創建動態和互動式 Web 應用程式的首選語言。

身為 Go 開發者,如果您不想使用 Javascript 但仍然實作響應式 Web 應用程式怎麼辦?

想像一下一個時尚的待辦事項清單應用程序,當您檢查任務時它會立即更新,而無需重新加載整頁。這就是Golang和htmx的力量!

結合 Go 和 htmx 使我們能夠創建響應式和互動式 Web 應用程序,而無需編寫一行 JavaScript。

在本部落格中,我們將探討如何使用 htmx 和 Golang 建立 Web 應用程式。 (它也可以與您喜歡的其他平台一起使用。)

作為學習,我們將為使用者實現基本的建立和刪除操作。

.htmx是什麼?

htmx 是一個現代 HTML 擴展,它增加了瀏覽器和伺服器之間的雙向通訊。

它允許我們在不編寫 JavaScript 的情況下建立動態網頁,因為它可以直接在 HTML 中存取 AJAX、伺服器發送的事件等。

htmx 是如何運作的?

  • 當使用者與具有 htmx 屬性的元素互動時(例如按一下按鈕),瀏覽器會觸發指定的事件。
  • htmx 攔截該事件並向屬性中指定的伺服器端端點傳送 HTTP 請求(例如,hx-get="/my-endpoint")。
  • 伺服器端端點處理請求並產生 HTML 回應。
  • htmx 接收回應並根據 hx-target 和 hx-swap 屬性更新 DOM。這可能涉及:

 — 取代整個元素的內容。
 — 在元素之前或之後插入新內容。
 — 將內容附加到元素的末端。

讓我們透過一個例子來更深入地理解它。

<button hx-get="/fetch-data" hx-target="#data-container">
   Fetch Data
</button>
<div>



<p>In the above code, when the button is clicked:</p>

<ol>
<li>htmx sends a GET request to /fetch-data.
</li>
<li>The server-side endpoint fetches data and renders it as HTML.</li>
<li>The response is inserted into the #data-container element.</li>
</ol>

<h3>
  
  
  Create and delete the user
</h3>

<p>Below are the required tools/frameworks to build this basic app.</p>

<ul>
<li>Gin (Go framework)</li>
<li>Tailwind CSS </li>
<li>htmx</li>
</ul>

<p><strong>Basic setup</strong> </p>

<ul>
<li>Create main.go file at the root directory.</li>
</ul>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

它設定了一個基本的 Go 伺服器,在連接埠 8080 上運作。
運行 go run main.go 來運行應用程式。

  • 在根目錄中建立一個 HTML 文件,用於渲染使用者清單。

users.html


   
      <title>Go + htmx app </title>
      <script src="https://unpkg.com/htmx.org@2.0.0" integrity="sha384-wS5l5IKJBvK6sPTKa2WZ1js3d947pvWXbPJ1OmWfEuxLgeHcEbjUUA5i9V5ZkpCw" crossorigin="anonymous"></script>
      <script src="https://cdn.tailwindcss.com"></script>
   
   



<blockquote>
<p>We have included,</p>

<p><strong>htmx</strong> using the script tag — <u>https://unpkg.com/htmx.org@2.0.0</u></p>

<p><strong>Tailwind CSS</strong> with cdn link —<br>
<u>https://cdn.tailwindcss.com</u></p>
</blockquote>

<p>Now, we can use Tailwind CSS classes and render the templates with htmx.</p>

<p>As we see in users.html, we need to pass users array to the template, so that it can render the users list. </p>

<p>For that let’s create a hardcoded static list of users and create a route to render users.html .</p>

<h3>
  
  
  Fetch users
</h3>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "net/http"
 "text/template"

 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.GET("/", func(c *gin.Context) {
  users := GetUsers()

  tmpl := template.Must(template.ParseFiles("users.html"))
  err := tmpl.Execute(c.Writer, gin.H{"users": users})
    if err != nil {
       panic(err)
    }
 })

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

type User struct {
 Name  string
 Email string
}

func GetUsers() []User {
 return []User{
  {Name: "John Doe", Email: "johndoe@example.com"},
  {Name: "Alice Smith", Email: "alicesmith@example.com"},
 }
}

我們新增了一條路由 / 來渲染使用者清單並提供靜態使用者清單(我們將提前新增使用者)。

僅此而已。重新啟動伺服器,我們造訪 — http://localhost:8080/看看是否渲染了使用者清單。它將呈現如下的用戶列表。

Golang   htmx   Tailwind CSS: Create a Responsive Web Application

創建用戶

建立檔案user_row.html。它將負責向用戶表添加新的用戶行。

使用者行.html

<button hx-get="/fetch-data" hx-target="#data-container">
   Fetch Data
</button>
<div>



<p>In the above code, when the button is clicked:</p>

<ol>
<li>htmx sends a GET request to /fetch-data.
</li>
<li>The server-side endpoint fetches data and renders it as HTML.</li>
<li>The response is inserted into the #data-container element.</li>
</ol>

<h3>
  
  
  Create and delete the user
</h3>

<p>Below are the required tools/frameworks to build this basic app.</p>

<ul>
<li>Gin (Go framework)</li>
<li>Tailwind CSS </li>
<li>htmx</li>
</ul>

<p><strong>Basic setup</strong> </p>

<ul>
<li>Create main.go file at the root directory.</li>
</ul>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

它從表單輸入取得姓名電子郵件並執行user_row.html

讓我們嘗試在表中新增一個使用者。造訪http://localhost:8080/並點擊新增使用者按鈕。

Golang   htmx   Tailwind CSS: Create a Responsive Web Application

耶耶!我們已成功將新用戶新增至清單? .

要深入了解詳細實施指南,請查看 Canopas 上的完整指南。


如果您喜歡所讀的內容,請務必點擊?按鈕! — 身為作家,這意味著整個世界!

我鼓勵您在下面的評論部分分享您的想法。您的意見不僅豐富了我們的內容,也激發了我們為您創作更有價值、內容更豐富的文章的動力。

編碼愉快! ?

以上是Golang htmx Tailwind CSS:建立響應式 Web 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
掌握GO弦:深入研究'字符串”包裝掌握GO弦:深入研究'字符串”包裝May 12, 2025 am 12:05 AM

你應該關心Go語言中的"strings"包,因為它提供了處理文本數據的工具,從基本的字符串拼接到高級的正則表達式匹配。 1)"strings"包提供了高效的字符串操作,如Join函數用於拼接字符串,避免性能問題。 2)它包含高級功能,如ContainsAny函數,用於檢查字符串是否包含特定字符集。 3)Replace函數用於替換字符串中的子串,需注意替換順序和大小寫敏感性。 4)Split函數可以根據分隔符拆分字符串,常用於正則表達式處理。 5)使用時需考慮性能,如

GO中的'編碼/二進制”軟件包:您的二進制操作首選GO中的'編碼/二進制”軟件包:您的二進制操作首選May 12, 2025 am 12:03 AM

“編碼/二進制”軟件包interingoisentialForHandlingBinaryData,oferingToolSforreDingingAndWritingBinaryDataEfficely.1)Itsupportsbothlittle-endianandBig-endianBig-endianbyteorders,CompialforOss-System-System-System-compatibility.2)

Go Byte Slice操縱教程:掌握'字節”軟件包Go Byte Slice操縱教程:掌握'字節”軟件包May 12, 2025 am 12:02 AM

掌握Go語言中的bytes包有助於提高代碼的效率和優雅性。 1)bytes包對於解析二進制數據、處理網絡協議和內存管理至關重要。 2)使用bytes.Buffer可以逐步構建字節切片。 3)bytes包提供了搜索、替換和分割字節切片的功能。 4)bytes.Reader類型適用於從字節切片讀取數據,特別是在I/O操作中。 5)bytes包與Go的垃圾回收器協同工作,提高了大數據處理的效率。

您如何使用'字符串”軟件包在GO中操縱字符串?您如何使用'字符串”軟件包在GO中操縱字符串?May 12, 2025 am 12:01 AM

你可以使用Go語言中的"strings"包來操縱字符串。 1)使用strings.TrimSpace去除字符串兩端的空白字符。 2)用strings.Split將字符串按指定分隔符拆分成切片。 3)通過strings.Join將字符串切片合併成一個字符串。 4)用strings.Contains檢查字符串是否包含特定子串。 5)利用strings.ReplaceAll進行全局替換。注意使用時要考慮性能和潛在的陷阱。

如何使用'字節”軟件包在GO中操縱字節切片(逐步)如何使用'字節”軟件包在GO中操縱字節切片(逐步)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

Go Bytes軟件包:有什麼選擇?Go Bytes軟件包:有什麼選擇?May 11, 2025 am 12:11 AM

thealternativestogo'sbytespackageincageincludethestringspackage,bufiopackage和customstructs.1)thestringspackagecanbeusedforbytemanipulationforbytemanipulationbybyconvertingbytestostostostostostrings.2))

操縱字節切片在GO:'字節”軟件包的功能操縱字節切片在GO:'字節”軟件包的功能May 11, 2025 am 12:09 AM

“字節”包裝封裝forefforeflyManipulatingByteslices,CocialforbinaryData,網絡交易和andfilei/o.itoffersfunctionslikeIndexForsearching,BufferForhandLinglaRgedLargedLargedAtaTasets,ReaderForsimulatingStreamReadReadImreAmreadReamReadinging,以及Joineffiter和Joineffiter和Joineffore

Go Strings套餐:弦樂操縱的綜合指南Go Strings套餐:弦樂操縱的綜合指南May 11, 2025 am 12:08 AM

go'sstringspackageIscialforficientficientsTringManipulation,uperingToolSlikestrings.split(),strings.join(),strings.replaceall(),andStrings.contains.contains.contains.contains.contains.contains.split.split(split()strings.split()dividesStringoSubSubStrings; 2)strings.joins.joins.joinsillise.joinsinelline joinsiline joinsinelline; 3);

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具