Go Fiber 한글 공식 문서
  • 🙇‍♀️안녕하세요
  • 🏠Home
    • 👋Welcome
    • 📁API
      • 📦Fiber
      • 🚀App
      • 🧠Ctx
      • 📋Constants
      • 🌎Client
      • 📃Log
      • 🧬Middleware
        • Adaptor
        • BasicAuth
        • Cache
        • Compress
        • CORS
        • CSRF
        • EarlyData
        • Encrypt Cookie
        • EnvVar
        • ETag
        • ExpVar
        • Favicon
        • FileSystem
        • Health Check
        • Helmet
        • Idempotency
        • Keyauth
        • Limiter
        • Logger
        • Monitor
        • Pprof
        • Proxy
        • Recover
        • Redirect
        • RequestID
        • Rewrite
        • Session
        • Skip
        • Timeout
    • 📁Guide
      • 🔌Routing
      • 🎭Grouping
      • 📝Templates
      • 🐛Error Handling
      • 🔎Validation
      • 🎣Hooks
      • ⚡Make Fiber Faster
    • 📁Extra
      • 🤔FAQ
      • 📊Benchmarks
  • 🧩Extra
    • 🧬Contrip
      • 👋Welcome
      • Casbin
      • Fgprof
      • Fiberi18n
      • Fibernewrelic
      • Fibersentry
      • Fiberzap
      • Fiberzerolog
      • JWT
      • LoadShed
      • Opafiber
      • Otelfiber
        • Example
      • Paseto
      • README
      • Swagger
      • Websocket
    • 📦Storage
      • 👋Welcome
      • ArangoDB
      • Azure Blob
      • Badger
      • Bbolt
      • Coherence
      • Couchbase
      • DynamoDB
      • Etcd
      • Memcache
      • Memory
      • Minio
      • MongoDB
      • MSSQL
      • MySQL
      • Nats
      • Pebble
      • Postgres
      • Redis
      • Ristretto
      • Rueidis
      • S3
      • ScyllaDb
      • SQLite3
    • 📃Template
      • 👋Welcome
      • Ace
      • Amber
      • Django
      • Handlebars
      • HTML
        • Golang Templates Cheatsheet
      • Jet
      • Mustache
      • Pug
      • Slim
Powered by GitBook
On this page
  • Basic Example
  • embed.FS 예제
  • innerHTML 예제
  1. Extra
  2. Template

HTML

PreviousHandlebarsNextGolang Templates Cheatsheet

Last updated 1 year ago


HTML은 Go의 공식 템플릿 엔진인 입니다. 원본 문법 설명서를 보려면 .

정보:

지정된 뷰 디렉토리 내의 모든 템플릿은 사용할 때의 성능을 높이기 위해 시작 시 분석 및 컴파일됩니다. 따라서 동일한 이름의 정의가 존재해서는 안 되며, 그렇지 않으면 서로 덮어쓰게 됩니다. 템플릿 작성에는 {{embed}} 태그를 사용해야 합니다.

Basic Example

./views/index.html

{{template "partials/header" .}}

<h1>{{.Title}}</h1>

{{template "partials/footer" .}}

./views/partials/header.html

<h2>Header</h2>

./views/partials/footer.html

<h2>Footer</h2>

./views/layouts/main.html

<!DOCTYPE html>
<html>
  <head>
    <title>Main</title>
  </head>

  <body>
    {{embed}}  
  </body>
</html>
package main

import (
	"log"
	
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/template/html/v2"
)

func main() {
	// 새 엔진 생성
	engine := html.New("./views", ".html")

	// 또는 임베드 시스템에서
	// 예제는 github.com/gofiber/embed를 참조하세요
	// engine := html.NewFileSystem(http.Dir("./views", ".html"))

	// Views에 엔진 전달
	app := fiber.New(fiber.Config{
		Views: engine,
	})

	app.Get("/", func(c *fiber.Ctx) error {
		// index 렌더링
		return c.Render("index", fiber.Map{
			"Title": "Hello, World!",
		})
	})

	app.Get("/layout", func(c *fiber.Ctx) error {
		// layouts/main 내의 index 렌더링
		return c.Render("index", fiber.Map{
			"Title": "Hello, World!",
		}, "layouts/main")
	})

	app.Get("/layouts-nested", func(c *fiber.Ctx) error {
		// layouts/nested/base 내의 layouts/nested/main 내의 index 렌더링
		return c.Render("index", fiber.Map{
			"Title": "Hello, World!",
		}, "layouts/nested/main", "layouts/nested/base")
	})

	log.Fatal(app.Listen(":3000"))
}

embed.FS 예제

package main

import (
    "log"
    "net/http"
    "embed"

    "github.com/gofiber/fiber/v2" 
    "github.com/gofiber/template/html"
)

//go:embed views/*
var viewsfs embed.FS

func main() {
    engine := html.NewFileSystem(http.FS(viewsfs), ".html")

    // Views에 엔진 전달 
    app := fiber.New(fiber.Config{
        Views: engine,
    })


    app.Get("/", func(c *fiber.Ctx) error {
        // index 렌더링 - views 디렉토리부터 시작 
        return c.Render("views/index", fiber.Map{
            "Title": "Hello, World!",  
        })
    })

    log.Fatal(app.Listen(":3000"))
}

그리고 시작점을 views 디렉토리로 변경합니다.

./views/index.html

{{template "views/partials/header" .}}

<h1>{{.Title}}</h1>

{{template "views/partials/footer" .}} 

innerHTML 예제

package main

import (
    "embed"
    "html/template"
    "log"
    "net/http"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/html" 
)

//go:embed views/*
var viewsfs embed.FS

func main() {
    engine := html.NewFileSystem(http.FS(viewsfs), ".html")
    engine.AddFunc(
        // unescape 함수 추가
        "unescape", func(s string) template.HTML {
            return template.HTML(s)  
        },
    )

    // Views에 엔진 전달
    app := fiber.New(fiber.Config{Views: engine})

    app.Get("/", func(c *fiber.Ctx) error {
        // index 렌더링
        return c.Render("views/index", fiber.Map{
            "Title": "Hello, <b>World</b>!",
        })
    })

    log.Fatal(app.Listen(":3000"))
}

그리고 시작점을 views 디렉토리로 변경합니다.

./views/index.html

<p>{{ unescape .Title}}</p>

HTML 출력

<p>Hello, <b>World</b>!</p>
🧩
📃
html/template
여기를 클릭하세요