Go Templates With TailwindCSS
This is a simple guide on how to setup TailwindCSS to work with your Golang templates.
Setup
To get started we need to install TailwindCSS
npm install -D tailwindcss
Then we’ll initilize TailwindCSS so that the tailwind.config.js
file is generated:
npx tailwindcss init
Then we’ll modify the tailwind.config.js
file to look like this:
module.exports = {
content: ["./templates/**/*.html"],
theme: {
extend: {},
},
plugins: [],
};
This ensures that the Tailwind CLI knows where to look for our templates using Tailwind classes. Then we’ll create a css input file containing Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;
Then we can start Tailwind CLI by running the following command:
npx tailwindcss -i ./src/input.css -o ./public/css/tw.css --watch
This will update the ouput tw.css
file any time we make changes to our html templates.
Next let’s add a simple template to test our server:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/public/css/tw.css" />
<title>Document</title>
</head>
<body>
<main>
<h1 class="text-2xl text-red-500">Hello world!</h1>
</main>
</body>
</html>
Note that we import /public/css/tw.css
as a stylesheet.
Next we can make a simple Go server to serve our application to see it in action.
package main
import (
"html/template"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/public/", http.FileServer(http.Dir(".")))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
tmpl := template.Must(template.ParseFiles("./templates/index.html"))
if err := tmpl.Execute(w, nil); err != nil {
// handle error
}
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
http.ListenAndServe(":8080", mux)
}
Now, when we run the application with the command go run main.go
and navigate to http://localhost:8080
, we will find a page that should look like this: