个人技术主页

多语言模板渲染与 Vue 基础测试展示

HTML 基础结构

标准的 HTML5 语义化结构模板,作为所有渲染的基础载体。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ .Title }}</title>
</head>
<body>
    <header>
        <h1>欢迎访问</h1>
    </header>
    <main>
        <!-- 动态内容区域 -->
        <div id="content">
            {{ .Content }}
        </div>
    </main>
</body>
</html>

Go 模板渲染 (html/template)

使用 Go 标准库 `html/template` 进行安全的服务端渲染,自动防止 XSS 攻击。

package main

import (
    "html/template"
    "net/http"
)

type PageData struct {
    Title   string
    Content string
    Tags    []string
}

func handler(w http.ResponseWriter, r *http.Request) {
    // 解析模板文件
    tmpl, err := template.ParseFiles("templates/index.html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 准备数据
    data := PageData{
        Title:   "Go 语言模板演示",
        Content: "这是由 Go 后端渲染的内容。",
        Tags:    []string{"Golang", "Backend", "Template"},
    }

    // 执行渲染并写入响应
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    tmpl.Execute(w, data)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Python 模板渲染 (Jinja2)

基于 Flask 框架和 Jinja2 引擎的动态页面渲染示例,支持复杂的逻辑控制。

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    # 模拟数据库查询结果
    user = {
        'username': 'DevUser',
        'role': 'Admin',
        'last_login': '2026-11-22'
    }
    # 渲染模板并传递变量
    return render_template('index.html', user=user)

if __name__ == '__main__':
    app.run(debug=True, port=5000)

# --- templates/index.html 内容 ---
# <h1>欢迎, {{ user.username }}!</h1>
# {% if user.role == 'Admin' %}
#     <p>您拥有管理员权限。</p>
# {% endif %}

Node.js 视图渲染 (EJS)

在 Express 框架中配置 EJS 模板引擎,实现前后端数据交互。

const express = require('express');
const path = require('path');
const app = express();

// 设置视图引擎和目录
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.get('/', (req, res) => {
    const products = [
        { id: 1, name: '笔记本电脑', price: 5999 },
        { id: 2, name: '机械键盘', price: 399 }
    ];
    
    // 渲染 index.ejs 并传入数据
    res.render('index', { title: '商品列表', items: products });
});

app.listen(3000, () => console.log('Server running on port 3000'));

// --- views/index.ejs 片段 ---
// <h2><%= title %></h2>
// <ul>
//   <% items.forEach(item => { %>
//     <li><%= item.name %> - ¥<%= item.price %></li>
//   <% }) %>
// </ul>

Vue.js 基础与单元测试

使用 Vue Test Utils 对组件进行挂载、数据模拟和断言测试。

import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  // 1. 测试组件渲染
  it('renders props.msg when passed', () => {
    const msg = 'Hello Vue Test!'
    const wrapper = shallowMount(HelloWorld, {
      props: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })

  // 2. 测试交互与状态变化
  it('increments count on button click', async () => {
    const wrapper = shallowMount(HelloWorld)
    const button = wrapper.find('button')
    
    // 初始状态
    expect(wrapper.vm.count).toBe(0)
    
    // 模拟点击
    await button.trigger('click')
    
    // 断言状态更新
    expect(wrapper.vm.count).toBe(1)
  })
})