首页 > 解决方案 > 模板中的 Golang ttf 字体

问题描述

我正在尝试让 TTF 字体在 golang 模板中工作,但它不会呈现字体。它显示为常规的 Times New Roman。我可以使用标准字体系列字体(例如 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>

标签: csstemplatesgotruetype

解决方案


您需要处理静态文件,将其添加到 main func 并将 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>

推荐阅读