search

Integrating Templ

Sep 12, 2024 am 10:20 AM

This is going to be a longer one as we need three (3) files now. Also, we need a static directory for files like favicon.ico, a css file (if you choose to use css), logo, or any other static file.

net/http docs. These are your best friend.

Let's begin, shall we?

Install and Set Up

Thankfully, the way Go is set up, this is a straight forward process.
go install github.com/a-h/templ/cmd/templ@latest
The above command gets you the templ binary (you did set your PATH, right?).
go get github.com/a-h/templ
This one loads templ into your go.mod.

That's it. Install and set up are done.

And the struggle

The most difficult part of this process, was getting styles.css to load properly. If you are not using a css file, you can skip the line regarding the static directory.

// File: /root/cmd/server/main.go
package main

import (
    [go mod module name]/internal/views
)
func main(){
    port := ":3000"
    home := templ.Component(views.Home())

    http.Handle("/", templ.Handler(home))
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

    log.Fatal(http.ListenAndServe(port, nil))
}

It looks more complicated than it really is. Lets look at this a step at a time.

port := ":3000"

port is, well, the port (I'm presuming you know what a port is). When passing the port to http.ListenAndServe(addr string, handler Handler), make sure you include :, else it will not go run or go build.

home := templ.Component(views.Home())

home is an instance of the Home function from home.templ.

http.Handle("/", templ.Handler(home))

All we are doing here, is passing home to templ's Handler(), which does the same thing http.Handler() does, only a little more specific. Here is the source to templ.Handler():

type Handler struct {
    h slog.Handler
    m *sync.Mutex
    w io.Writer
}

This Handler is assigned to the root dir pattern and then used by ServeMux, the http multiplexer. A fancy way of saying it handles all the paths for a given Top Level Domain.

http.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))

This is a long one but can easily be digested. http.Handle(pattern string, handler Handler) we went over, above. The pattern, in this case, is the static directory. The Handler is made of Higher-Order Functions. That simply means that functions are treated as data, as well, and can be assigned to variables and/or passed as a parameter.

In this case, we're passing http.Dir("./static"). http.Dir(dir string) is used to implement a native FileSystem (opens the dir), and is limited to the $pwd/$cwd. That is why we pass ".". We're starting from the root. This is passed into http.FileServer(root FileSystem) Handler which returns the needed Handler. Then we pass that into http.StripPrefix(pattern string, fs FileSystem) which does exactly what it sounds like, removes the directory name from the path. The real benefit, when you think about what it's doing, /static is now /, which is root. So where does the css apply? On the home page.

That wasn't so bad, was it?

log.Fatal(http.ListenAndServe(port, nil))

http.ListenAndServe(addr string, handler Handler) error is the last part. This function also returns non-nil error values, so error handling is STRONGLY advised. log.Fatal(v ...any) takes any type and is "equivalent to calling Print() on os.Exit(1)"source. Meaning, if the program exits with any other value than 0 (i.e. crash), it will log the event.

At some point, I'm going to look into http.ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error. Right now, TLS is being served by my host (not self-hosted).

And with that, main.go is done for now.

Templ templates

Our first template, will be ./internal/views/layout.templ. This file will handle the way the page is displayed. If you're coming from React or Nextjs, it's your page.tsx file.

// File: /root/internal/views/layout.templ
package views

templ Layout( title string ){
    
    
        
            <link rel="icon" type="image/x-icon" href="/static/favicon.ico">
            <link rel="stylesheet" type="text/css" href="/static/styles.css">
            <title>{title}</title>
        
        
            {children ...}
        
    
}

Really straight forward.

The next template is home.templ. This will contain the contents of /.

// File: /root/internal/views/home.templ
package views

templ Home(){
    @Layout("Home")
}

Passing "Home" into @Layout(title string) sets the pages title to, you guessed it, Home.

Wrapping it up

Okay, like I said in the beginning, it's a lot this time. Two (2) more things and we're finished with implementing and testing templ.

# 1 - make sure `go.sum` is up-to-date
go mod tidy
# 2 - have templ generate go files
templ generate
# 3a - build it out
go build ./cmd/server/main.go
./main
# 3b - or test it out
go run ./cmd/server/main.go
# you can shorten the path to
go run ./cmd/server/.

You should see your go/templ web page in all of its glory; even if it's burning your retinas because you forgot to change the background color in your css.

Addendum

You can pass contents templ.Component as a parameter if you choose to use jsx tags as templ templates. Likewise, templ also provides a css components for custom templates.

Errata

If you spot an error, are having any troubles, or I missed something, please, feel free to leave a comment and I'll do my best to update and/or help.

Up Next

Since our web sites are going to change (adding content), we're going to go through the steps to set up a GitHub-Hosted Runner to handle building out the files and commit-ting them so we can deploy it.

I will be adding a git repo for this project, in the future. It will have all of the files we're writing and a .github/go.yml file for GitHub Actions.

Integrating Templ

The above is the detailed content of Integrating Templ. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

How to use reflection comparison and handle the differences between three structures in Go?How to use reflection comparison and handle the differences between three structures in Go?Apr 02, 2025 pm 05:15 PM

How to compare and handle three structures in Go language. In Go programming, it is sometimes necessary to compare the differences between two structures and apply these differences to the...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor