Views

Learn how to render views in Caesar.

Overview

The recommended way to render views is to use Templ which is a fast and simple Go template engine. Templ is a great template engine, allowing to write HTML while making use of Go constructs.

Rendering pages from the router

A page can be rendered directly from the router, by making use of the ctx.Render method. This method takes the name of the view to render, as well as the data to pass to the view

package config

import (
	"starter_kit/views/pages"

	caesar "github.com/caesar-rocks/core"
)

func RegisterRoutes() *caesar.Router {
	router := caesar.NewRouter()
	router.Render("/", pages.WelcomePage())

	return router
}

Internally, the ctx.Render method will create a GET route for the specified path, and will render the page when the route is matched.

Rendering pages from a controller

Pages can also be rendered from a controller. To render a page from a controller, you can make use of the ctx.Render method, available from the CaesarCtx struct.

package controllers

import (
	"starter_kit/views/pages"

	caesar "github.com/caesar-rocks/core"
)

type WelcomeController struct{}

func NewWelcomeController() *WelcomeController {
	return &WelcomeController{}
}

func (c *WelcomeController) Show(ctx *caesar.CaesarCtx) error {
	return ctx.Render(pages.WelcomePage())
}