/* * Micro Service * Package: gitlab.hexacode.org/go-libs/microservice * Maintainer: Azzis Arswendo * * Copyright (C) 2023 Hexacode Teknologi Indonesia * All Rights Reserved */ // Example from string: // tmpl, err := config.NewTemplate("Hello {{ name }}") // // Example from file: // tmpl, err := config.NewTemplateFromFile("template.html") // // Example Render: // render, err := tmpl.Render(hctypes.Dict{"name": "John Doe"}) // Please see https://github.com/noirbizarre/gonja for more details template package config import ( "encoding/json" "os" "github.com/noirbizarre/gonja" "github.com/noirbizarre/gonja/exec" "gitlab.hexacode.org/go-libs/hctypes" ) // Template represents a mail template type Template struct { template *exec.Template // The template instance } // NewTemplate creates a new Template // // template: The template // Returns: *Template func NewTemplate(template string) (*Template, error) { tmpl, err := gonja.FromString(template) return &Template{ template: tmpl, }, err } // NewTeplateFromFile creates a new Template // // template_file: The template file // Returns: *Template func NewTemplateFromFile(template_file string) (*Template, error) { data, err := os.ReadFile(template_file) if err != nil { return nil, err } tmpl, err := gonja.FromBytes(data) return &Template{ template: tmpl, }, err } // Render renders the template // // data: The data // Returns: string func (t *Template) Render(data hctypes.Dict) (string, error) { raw := map[string]interface{}{} err := json.Unmarshal([]byte(data.ToJson()), &raw) if err != nil { return "", err } return t.template.Execute(raw) }