>백엔드 개발 >Golang >Golang htmx Tailwind CSS: 반응형 웹 애플리케이션 만들기

Golang htmx Tailwind CSS: 반응형 웹 애플리케이션 만들기

Barbara Streisand
Barbara Streisand원래의
2024-11-23 16:05:311113검색

배경

오늘날의 웹 개발 환경에서 JavaScript는 동적인 대화형 웹 애플리케이션을 만들기 위해 오랫동안 선택되어 왔습니다.

Go 개발자로서 Javascript를 사용하고 싶지 않지만 여전히 반응형 웹 애플리케이션을 구현하고 싶다면 어떻게 해야 할까요?

전체 페이지를 다시 로드하지 않고도 작업을 확인하면 즉시 업데이트되는 멋진 할 일 목록 앱을 상상해 보세요. 이것이 바로 Golang과 htmx의 힘입니다!

Go와 htmx를 결합하면 JavaScript를 한 줄도 작성하지 않고도 반응형 및 대화형 웹 애플리케이션을 만들 수 있습니다.

이 블로그에서는 htmx와 Golang을 사용하여 웹 애플리케이션을 구축하는 방법을 살펴보겠습니다. (다른 즐겨찾는 플랫폼에서도 사용할 수 있습니다.)

학습의 일환으로 사용자를 위한 기본 생성 및 삭제 작업을 구현해 보겠습니다.

htmx란 무엇인가요?

htmx는 브라우저와 서버 간의 양방향 통신을 추가하는 최신 HTML 확장 프로그램입니다.

AJAX, 서버 전송 이벤트 등에 대한 액세스를 HTML로 직접 제공하므로 JavaScript를 작성하지 않고도 동적 웹 페이지를 만들 수 있습니다.

htmx는 어떻게 작동하나요?

  • 사용자가 htmx 속성이 있는 요소와 상호작용(예: 버튼 클릭)하면 브라우저가 지정된 이벤트를 트리거합니다.
  • htmx는 이벤트를 가로채고 속성에 지정된 서버측 엔드포인트(예: hx-get="/my-endpoint")에 HTTP 요청을 보냅니다.
  • 서버측 엔드포인트는 요청을 처리하고 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")
}

포트 8080에서 실행되는 기본 Go 서버를 설정합니다.
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 파일을 만듭니다. 사용자 테이블에 새 사용자 행을 추가하는 역할을 담당합니다.

user_row.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: 반응형 웹 애플리케이션 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript golang css ajax html Static if for try Directory Attribute Event delete dom this background input table http Access
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Why Might Go의 `go f(); g()` \"21\" 대신 \"20\"을 인쇄하시겠습니까?다음 기사:Why Might Go의 `go f(); g()` \"21\" 대신 \"20\"을 인쇄하시겠습니까?

관련 기사

더보기