模板中的 Golang ttf 字体

Golang ttf font in template

我试图让 TTF 字体在 golang 模板中工作,但它不会呈现字体。它显示为常规的 Times New Roman。我可以使用标准字体系列字体(ex verdana 或 'helvetica')更改字体,但我无法导入 TTF。

关于 TTF 字体,我似乎只能找到用于向图像添加文本的库,但我想更改网络字体。我怎样才能做到这一点?

项目结构是

这里是相关的golang代码:

import (
    "fmt"
    "net/http"
    "text/template"
)
type Portal struct{
    Title string
}
func main(){
    //Create MUX Routing handlers
    http.HandleFunc("/", portal)

    //Start WebServer
    if err := http.ListenAndServe(":1234", nil); err != nil{ panic(err) }
}
func portal(w http.ResponseWriter, r *http.Request){
    //Create template
    tmpl, _ := template.ParseFiles("./html_templates/portal.html")

    //Populate struct
    portal := Portal{
        Title: "title",
    }

    //Execute template with struct data
    tmpl.Execute(w, portal)
}

以及相关的HTML:

<html>
<head>
    <title>{{ .Title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        @font-face {
            font-family: 'comfortaaRegular';
            src: url('Comfortaa-Regular.ttf');
            src: local('comfortaaRegular'), 
                 local('Comfortaa-Regular.ttf'), 
                 url('Comfortaa-Regular.ttf') format('truetype'),
        }
        body{ font-family: 'comfortaaRegular' }
    </style>
</head>
<body>
    <p>test/p>
</body>
</html>

您需要处理静态文件,将其添加到主函数并在您的模板中将 url 设置为 /static/Comfortaa-Regular.ttf

//Create MUX Routing for static
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

这是完整的工作代码

package main

import (
    "net/http"
    "text/template"
)

type Portal struct{
    Title string
}

func main(){
    //Create MUX Routing handlers
    http.HandleFunc("/", portal)

    //Create MUX Routing for static
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    //Start WebServer
    if err := http.ListenAndServe(":1234", nil); err != nil{ panic(err) }
}

func portal(w http.ResponseWriter, r *http.Request){
    //Create template
    tmpl, _ := template.ParseFiles("./html_templates/portal.html")

    //Populate struct
    portal := Portal{
        Title: "title",
    }

    //Execute template with struct data
    tmpl.Execute(w, portal)
}

和模板

<head>
    <title>{{ .Title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        @font-face {
            font-family: 'comfortaaRegular';
            src: url('/static/Comfortaa-Regular.ttf');
            src: local('comfortaaRegular'),
                 local('Comfortaa-Regular.ttf'),
                 url('/static/Comfortaa-Regular.ttf') format('truetype'),
        }
        body{ font-family: 'comfortaaRegular' }
    </style>
</head>
<body>
    <p>test</p>
</body>
</html>