如何在Yew(Rust)中渲染自定义字体?SSR环境字体导入问题
在Yew(SSR模式)中导入自定义字体的可行方案
完全可以在Yew的SSR项目中使用自定义字体,核心是处理好静态资源的路径配置与托管,以下是具体步骤:
1. 整理项目静态资源结构
将你的windows_command_prompt.ttf字体文件放到项目的静态资源目录下,比如创建static/fonts/文件夹,把字体文件放入其中,最终路径为static/fonts/windows_command_prompt.ttf。
2. 修正@font-face配置
调整CSS中的路径为绝对路径(相对于网站根目录),同时补充字体格式声明,确保浏览器能正确识别:
@font-face { font-family: "terminal"; src: url("/fonts/windows_command_prompt.ttf") format("truetype"); font-weight: normal; font-style: normal; }
注:如果你的静态资源托管路径不是根目录,需要对应调整url中的前缀,比如静态资源托管在
/static/下,路径就改成/static/fonts/windows_command_prompt.ttf。
3. 确保静态资源被正确托管
- 如果你使用Trunk(Yew官方推荐的构建工具),它默认会将
static/目录下的资源打包并托管,直接运行trunk serve或trunk build即可,无需额外配置。 - 如果你是自行搭建SSR服务(比如Yew配合Axum),需要在服务器中添加静态资源托管逻辑,比如Axum中可以用
ServeDir来托管static/目录:
use axum::{routing::get, Router}; use std::net::SocketAddr; #[tokio::main] async fn main() { let app = Router::new() // 托管静态资源 .nest_service("/", axum::serve_dir::ServeDir::new("static")) // 你的SSR路由 .route("/", get(your_ssr_handler)); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); }
4. 在Yew组件中使用字体
在组件的样式中直接引用自定义字体即可:
use yew::prelude::*; #[function_component(App)] pub fn app() -> Html { html! { <div style="font-family: 'terminal', monospace;"> {"这是使用自定义终端字体的文本内容"} </div> } }
内容的提问来源于stack exchange,提问作者LocalTrash
相关产品推荐
相关产品推荐

