HTML templating engine AddFunc: translations #3106
Unanswered
xttlegendapi
asked this question in
Q&A
Replies: 1 comment
-
here a little example of an approach for this package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html/v2" // HTML-Template-Engine
)
// getCommon function returns a map with common data for templates
func getCommon(c *fiber.Ctx) fiber.Map {
return fiber.Map{
// Store the accepted language in the map (either "de" for German or "en" for English)
"Lang": c.AcceptsLanguages("de", "en"),
}
}
func main() {
// Initialize the HTML template engine with the views directory and .html as the extension
engine := html.New("./views", ".html")
// Add a custom function "Translate" to the template engine
engine.AddFunc("Translate", func(key string, lang string) string {
// Check if the language is German ("de")
if lang == "de" {
// In a real-world scenario, you would use a more robust data source (e.g., database, JSON, SQLite) for translations
switch key {
case "hello":
return "Hallo"
case "goodbye":
return "Auf Wiedersehen"
default:
return key
}
}
// Default to returning the original key if the language isn't German
return key
})
// Initialize the Fiber app with the configured HTML template engine
app := fiber.New(fiber.Config{
Views: engine, // Set the HTML template engine
})
// Define a route for the homepage
app.Get("/", func(c *fiber.Ctx) error {
// Render the index.html template with the common data provided by getCommon
return c.Render("index", getCommon(c))
})
// Start the Fiber server on port 3000
app.Listen(":3000")
} /views/index.html <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{Translate "hello" .Lang}}</h1>
<p>{{Translate "goodbye" .Lang}}</p>
</body>
</html> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Beta Was this translation helpful? Give feedback.
All reactions