模板渲染

概述

Silent框架支持多种模板引擎,让您能够轻松实现动态页面渲染。本指南将介绍如何在Silent框架中高效使用模板引擎。

基本用法

1. 配置模板引擎

use silent::prelude::*;
use silent::template::Template;

async fn create_app() -> Router {
    let app = Router::new();
    app.template("templates", "html")
}

2. 创建模板文件

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

3. 渲染模板

use silent::response::Template;

async fn index() -> Template {
    let mut context = Context::new();
    context.insert("title", "首页");
    context.insert("message", "欢迎使用Silent框架");
    Template::new("index").context(context)
}

高级特性

1. 模板继承

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
    <title><div data-gb-custom-block data-tag="block"></div></title>
</head>
<body>
    <div data-gb-custom-block data-tag="block"></div>

</body>
</html>

<!-- templates/page.html -->

<div data-gb-custom-block data-tag="extends" data-0='base.html'></div>

<div data-gb-custom-block data-tag="block">页面标题</div>

<div data-gb-custom-block data-tag="block">

    <h1>页面内容</h1>

</div>

2. 局部模板

<!-- templates/header.html -->
<header>
    <nav>{{ navigation }}</nav>
</header>

<!-- templates/page.html -->

<div data-gb-custom-block data-tag="include" data-0='header.html'></div>

<main>{{ content }}</main>

性能优化

  1. 模板缓存

    • 启用模板预编译

    • 使用模板缓存

    • 避免频繁重新加载

  2. 渲染优化

    • 减少模板嵌套层级

    • 避免复杂的模板逻辑

    • 使用局部更新策略

  3. 数据处理

    • 预处理模板数据

    • 使用视图模型

    • 避免在模板中处理复杂逻辑

最佳实践

  1. 目录结构

    templates/
    ├── layouts/
    │   └── base.html
    ├── partials/
    │   ├── header.html
    │   └── footer.html
    └── pages/
        └── index.html
  2. 错误处理

    async fn render_template() -> Result<Template, Error> {
        let template = Template::new("index")
            .context(context)
            .map_err(|e| Error::TemplateError(e.to_string()))?;
        Ok(template)
    }
  3. 国际化支持

    use silent::i18n::I18n;
    
    async fn create_app() -> Router {
        let app = Router::new();
        app.template("templates", "html")
           .i18n("locales", vec!["zh-CN", "en-US"])
    }

调试技巧

  1. 开发模式

    • 启用模板自动重载

    • 显示详细错误信息

    • 使用调试工具

  2. 错误页面

    <!-- templates/error.html -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>错误 - {{ status }}</title>
    </head>
    <body>
        <h1>{{ message }}</h1>
        

```

安全考虑

  1. XSS防护

    • 自动转义HTML字符

    • 使用安全的过滤器

    • 验证用户输入

  2. CSRF保护

    • 添加CSRF令牌

    • 验证表单提交

    • 使用安全头部

参考示例

完整的示例代码可以在Silent框架的examples目录中找到:

  • examples/templates - 基本的模板渲染示例

  • examples/templates-advanced - 高级模板功能示例

常见问题解决

  1. 模板不存在

    • 检查模板路径配置

    • 验证文件权限

    • 确认文件名大小写

  2. 渲染错误

    • 检查语法错误

    • 验证变量存在

    • 确认数据类型

Last updated

Was this helpful?