我正在尝试让TTF字体在golang模板中工作,但它不会呈现该字体。它显示为常规的Times New Roman。我可以使用标准字体系列字体(例如verdana或'helvetica')更改字体,但是我无法导入TTF。
我似乎能找到的有关TTF字体的所有东西都是将文本添加到图像的库,但是我想更改Web字体。我该如何实现?
项目的结构是
以下是相关的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>
答案 0 :(得分:1)
您需要处理静态文件,将其添加到主功能并将模板中的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>