getting started with template function in gin framework

  • Using the gin framework,return string types,JSON types,XML types ,struct types,JSONP type data.
  • the use of template and template syntax
  • Access mysql using the ORM packag

#1.Custom template function

#2.template nesting

#3.static file service

#Define the function body

// Time stamp converted to data function
func UnixToTime(timestamp int) string {
	fmt.Println(timestamp)
	t := time.Unix(int64(timestamp), 0)
	return t.Format("2006-01-02 15:04:05")
}

#Register a function with gin

	//custom template function
	r.SetFuncMap(template.FuncMap{
		"UnixToTime": UnixToTime,
	})

#create main.go

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	"time"
)

// Time stamp converted to data function
func UnixToTime(timestamp int) string {
	fmt.Println(timestamp)
	t := time.Unix(int64(timestamp), 0)
	return t.Format("2006-01-02 15:04:05")
}

func main() {
	r := gin.Default()
	//custom template function
	r.SetFuncMap(template.FuncMap{
		"UnixToTime": UnixToTime,
	})

	//Configure template engine to load everything in the template
	r.LoadHTMLGlob("templates/**/*")
	//Render templates using the gin framework
	r.GET("/news", func(c *gin.Context) {

		c.HTML(http.StatusOK, "news/index.html", gin.H{
			"title": "news page",
			"date":  1667538183,
		})
	})
	r.Run(":8088")
}

#create news/index.html

{{define "news/index.html"}}

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<!--Before conversion-->
<p>
    {{.date}}
</p>
<!--After conversion-->
{{UnixToTime .date}}
{{Add 3 3}}

</body>
</html>
{{end}}
go run main.go

//Listening and serving HTTP on :8088
//[GIN] 2022/11/04 - 01:17:42 | 200 |     712.682µs |       127.0.0.1 | GET      //"/news"

http://localhost:8088/news

//1667538183
//2022-11-04 01:03:03  6

#2.template nesting

{{template "public/page_header.html" .}}

#3.static file service

#Register a static file router with gin

//The front static indicates the route,and the back static indicates the path
r.Static("/static","./static")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值