css - 模板中的 Golang ttf 字体
问题描述
我正在尝试让 TTF 字体在 golang 模板中工作,但它不会呈现字体。它显示为常规的 Times New Roman。我可以使用标准字体系列字体(例如 verdana 或“helvetica”)更改字体,但我无法导入 TTF。
我似乎能找到的关于 TTF 字体的所有内容都是用于向图像添加文本的库,但我想更改网络字体。我怎样才能做到这一点?
项目结构是
- /html_templates/portal.html
- /html_teplates/Comfortaa-Regular.ttf
- main.go
这是相关的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>
解决方案
您需要处理静态文件,将其添加到 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>
推荐阅读
- python - 为什么在没有实例化的情况下执行类中的语句?
- python - Python类不识别列表
- firebase - Flutter Firebase 时间戳搜索查询
- python - 尝试使用 YouTube API 每小时检查一次视频的观看次数。可以使用 Python 来存储数据还是需要 PHP?
- tensorflow - 卷积神经网络的训练和测试
- node.js - 如何将模块从 Electron 应用程序暴露给外部模块
- c++ - c++ char*、字符串指针和strcmp问题
- android - 如何在Android中更改List View的第一个内容的属性
- r - R聚合多列
- r - 提取带有或不带有空格和标点符号的子字符串时出现问题?