rust web 框架 Loco 新建一个 HTML 页面

文章目录

    虽然 Loco 主推的是前后端分离的方式写页面,但是我还是喜欢后端渲染的 HTML 页面。

    因为我的使用场景,大部分不适用前后端分离:

    • 后端渲染的页面更 SEO 友好
    • 页面需要多语言支持,而前端实现并不合适。例如如果支持 10 门语言,总不能一次加载所有语言吧。
    • 前端技术更新过快,而且毫无意义。不想耗费过多的时间去跟进。

    言归正传。

    实际上 loco 官方文档中介绍 HTML template view 还是相对简单,要了解 view 的全面可以参考 loco 的一个 demo:

    https://github.com/loco-rs/loco/blob/master/examples/demo/src/views/dashboard.rs

    新建 HTML 模板

    例如,使用 loco 默认创建的一个 HTML 模板。

    > cat assets/views/home/hello.html
    
    <html><body>
      <img src="/static/image.png" width="200"/>
      <br/>
      find this tera template at <code>assets/views/home/hello.html</code>:
      <br/>
      <br/>
      {{ t(key="hello-world", lang="en-US") }},
      <br/>
      {{ t(key="hello-world", lang="de-DE") }}
    
    </body></html>
    

    新建 View

    src/views/hello.rs

    use loco_rs::prelude::*;
    use serde_json::json;
    
    /// Home view
    ///
    /// # Errors
    ///
    /// This function will return an error if render fails
    pub fn index(v: &impl ViewRenderer) -> Result<Response> {
        format::render().view(v, "home/hello.html", json!({}))
    }
    

    src/views/mod.rs 中添加:

    pub mod hello;
    

    新建 Controller

    src/controllers/hello.rs

    #![allow(clippy::unused_async)]
    use loco_rs::prelude::*;
    
    use crate::views;
    
    /// Renders the dashboard home page
    ///
    /// # Errors
    ///
    /// This function will return an error if render fails
    pub async fn render_index(ViewEngine(v): ViewEngine<TeraView>) -> Result<Response> {
        views::hello::index(&v)
    }
    
    pub fn routes() -> Routes {
        Routes::new()
            .prefix("hello")
            .add("/", get(render_index))
    }
    

    src/controllers/mod.rs 中添加:

    pub mod hello;
    

    添加路由

    src/app.rs

    .add_route(controllers::hello::routes())
    

    这个风格跟 django 很像,将一个 web 网站拆分为 N 个小的 app (例如文章管理,跟投票功能就是两个相对独立的 app),每个 app 有独立的路由。
    我自己维护的 golang gin 项目也是采用的这个风格。

    没想到 loco 也是这样设计的,估计 Rails 也是吧。

    切换 static 目录

    最后不要忘了切换 static 目录为 server-side 的配置 (默认为 client-side, 即前后端分离方案的前端部分)。

    打开 config/development.yaml 文件:

    • 取消 server-side 的注释
    • 注释掉 client-side 的配置
      # server-side static assets config # for use with the view_engine in initializers/view_engine.rs # static: enable: true must_exist: true precompressed: false folder: uri: "/static" path: "assets/static" fallback: "assets/static/404.html" # client side app static config #static: # enable: true # must_exist: true # precompressed: false # folder: # uri: "/" # path: "frontend/dist" # fallback: "frontend/dist/index.html"

    注意:如果不进行这步配置修改,会发现页面中的图片无法加载,报 404 错误。

    测试

    启动 loco 服务:

    cargo loco start
    

    然后,浏览器中访问:

    http://localhost:3000/hello

    即可看到:

    rust loco server side page

    参考

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式