You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过多语言JSON文件替换index.html中的title值?

多语言JSON替换HTML Title的实现方案

方法一:前端JavaScript动态加载替换

适合纯静态页面,无需构建工具,浏览器端实时加载对应语言文件并替换标题。

操作步骤

  • 先调整index.html结构,预留默认标题:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>默认管理标题</title>
    <script src="i18n.js"></script>
</head>
<body>
    <!-- 页面内容 -->
</body>
</html>
  • 创建i18n.js文件,处理语言加载与标题替换:
// 从URL参数获取语言标识,比如?lang=de,默认用英文
const urlParams = new URLSearchParams(window.location.search);
const currentLang = urlParams.get('lang') || 'en';

// 加载对应语言的JSON文件
fetch(`./${currentLang}.json`)
    .then(res => res.json())
    .then(data => {
        document.title = data['concurrent-deviceManagement-manage'];
    })
    .catch(err => console.error('语言文件加载失败:', err));

补充说明

  • 可替换语言检测逻辑,比如用navigator.language自动适配浏览器默认语言
  • 确保JSON文件与index.html路径匹配,避免加载失败

方法二:构建阶段批量替换(工程化项目)

如果用Webpack、Vite这类构建工具,可在打包时直接生成多语言版本的HTML文件,提前替换标题。

Vite示例(搭配vite-plugin-html)

  • 安装插件:
npm install vite-plugin-html --save-dev
  • 配置vite.config.js:
import { defineConfig } from 'vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import fs from 'fs';
import path from 'path';

// 读取目录下所有JSON语言文件
const langFiles = fs.readdirSync('./').filter(file => file.endsWith('.json'));
const langPages = langFiles.map(file => {
    const lang = file.replace('.json', '');
    const langData = JSON.parse(fs.readFileSync(path.resolve(__dirname, file), 'utf-8'));
    return {
        filename: `${lang}.html`,
        template: './index.html',
        inject: {
            data: { title: langData['concurrent-deviceManagement-manage'] }
        }
    };
});

export default defineConfig({
    plugins: [createHtmlPlugin({ minify: true, pages: langPages })]
});
  • 修改index.html的title为模板变量:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <!-- 页面内容 -->
</body>
</html>

补充说明

  • 构建完成后会生成对应语言的HTML文件(如en.html、fr.html),每个文件的title已替换为对应语言内容
  • Webpack项目可使用html-webpack-plugin配合自定义模板实现相同逻辑

内容的提问来源于stack exchange,提问作者Lordke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:31:14