...

Source file src/gitlab.hexacode.org/go-libs/microservice/config/template.go

Documentation: gitlab.hexacode.org/go-libs/microservice/config

     1  /*
     2   * Micro Service
     3   * Package: gitlab.hexacode.org/go-libs/microservice
     4   * Maintainer: Azzis Arswendo <azzis@hexacode.org>
     5   *
     6   * Copyright (C) 2023 Hexacode Teknologi Indonesia
     7   * All Rights Reserved
     8   */
     9  
    10  // Example from string:
    11  // tmpl, err := config.NewTemplate("Hello {{ name }}")
    12  //
    13  // Example from file:
    14  // tmpl, err := config.NewTemplateFromFile("template.html")
    15  //
    16  // Example Render:
    17  // render, err := tmpl.Render(hctypes.Dict{"name": "John Doe"})
    18  // Please see https://github.com/noirbizarre/gonja for more details template
    19  
    20  package config
    21  
    22  import (
    23  	"encoding/json"
    24  	"os"
    25  
    26  	"github.com/noirbizarre/gonja"
    27  	"github.com/noirbizarre/gonja/exec"
    28  	"gitlab.hexacode.org/go-libs/hctypes"
    29  )
    30  
    31  // Template represents a mail template
    32  type Template struct {
    33  	template *exec.Template // The template instance
    34  }
    35  
    36  // NewTemplate creates a new Template
    37  //
    38  // template: The template
    39  // Returns: *Template
    40  func NewTemplate(template string) (*Template, error) {
    41  	tmpl, err := gonja.FromString(template)
    42  	return &Template{
    43  		template: tmpl,
    44  	}, err
    45  }
    46  
    47  // NewTeplateFromFile creates a new Template
    48  //
    49  // template_file: The template file
    50  // Returns: *Template
    51  func NewTemplateFromFile(template_file string) (*Template, error) {
    52  	data, err := os.ReadFile(template_file)
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  
    57  	tmpl, err := gonja.FromBytes(data)
    58  	return &Template{
    59  		template: tmpl,
    60  	}, err
    61  }
    62  
    63  // Render renders the template
    64  //
    65  // data: The data
    66  // Returns: string
    67  func (t *Template) Render(data hctypes.Dict) (string, error) {
    68  	raw := map[string]interface{}{}
    69  	err := json.Unmarshal([]byte(data.ToJson()), &raw)
    70  	if err != nil {
    71  		return "", err
    72  	}
    73  	return t.template.Execute(raw)
    74  }
    75  

View as plain text