阿里云主机折上折
  • 微信号
Current Site:Index > Internationalization implementation translates this sentence into English, outputting only plain text without any additional content.

Internationalization implementation translates this sentence into English, outputting only plain text without any additional content.

Author:Chuan Chen 阅读数:52872人阅读 分类: ECharts

Internationalization Implementation

ECharts, as a popular data visualization library, supports chart rendering in multilingual environments. The internationalization (i18n) feature allows developers to dynamically switch text content in charts according to user language preferences, including tooltips, legends, axis labels, etc. By configuring language packs and locale settings, charts can be easily adapted to different language environments.

Language Pack Configuration

ECharts provides built-in language packs covering common languages such as English, Chinese, Japanese, etc. After importing a language pack, register it using the echarts.registerLocale method and specify the language when initializing the chart. For example, the following code demonstrates how to load English and Chinese language packs:

// Import ECharts and language packs
import * as echarts from 'echarts';
import 'echarts/i18n/langEN';
import 'echarts/i18n/langZH';

// Register the English language pack
echarts.registerLocale('EN', {
  time: {
    month: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    dayOfWeek: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  }
});

// Specify the language when initializing the chart
const chart = echarts.init(document.getElementById('chart-container'), null, {
  locale: 'EN' // or 'ZH' to switch to Chinese
});

Dynamic Language Switching

In practical applications, users may need to switch languages dynamically. This can be achieved by destroying and reinitializing the chart. Here is a complete example:

let currentLang = 'EN';

function initChart(lang) {
  const chartDom = document.getElementById('chart-container');
  const chart = echarts.getInstanceByDom(chartDom);
  if (chart) {
    chart.dispose();
  }
  echarts.init(chartDom, null, { locale: lang });
  // Reset the chart configuration
  chart.setOption({
    title: { text: lang === 'EN' ? 'Sales Data' : '销售数据' },
    xAxis: { data: ['Q1', 'Q2', 'Q3', 'Q4'] },
    yAxis: {},
    series: [{ type: 'bar', data: [120, 200, 150, 80] }]
  });
}

// Language switch button event
document.getElementById('switch-lang').addEventListener('click', () => {
  currentLang = currentLang === 'EN' ? 'ZH' : 'EN';
  initChart(currentLang);
});

Custom Translation Content

If the built-in language packs do not meet requirements, custom translations can be added. For example, overriding default tooltip text:

echarts.registerLocale('CUSTOM_EN', {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    data: ['Direct', 'Email', 'Search Engine']
  }
});

Locale Format Adaptation

In addition to text translation, internationalization also involves handling locale-specific formats for dates, numbers, etc. ECharts supports specifying locale settings via the locale configuration:

echarts.init(dom, null, {
  locale: {
    decimalPoint: '.', // Decimal point symbol
    thousandsSep: ',', // Thousands separator
    dateFormat: 'MMM d, yyyy' // Date format
  }
});

Multilingual Chart Components

For complex charts, it may be necessary to handle multilingual text for individual components. For example, registering multilingual names for map components:

echarts.registerMap('world', {
  // English map names
  name: 'World',
  regions: [
    { name: 'China', label: { formatter: '{b}' } },
    { name: 'United States', label: { formatter: '{b}' } }
  ]
}, {
  // Chinese map names
  name: '世界',
  regions: [
    { name: '中国', label: { formatter: '{b}' } },
    { name: '美国', label: { formatter: '{b}' } }
  ]
});

Internationalization for Server-Side Rendering

In server-side rendering (SSR) scenarios, ensure the language pack matches the client-side. In Node.js, this can be achieved as follows:

const echarts = require('echarts');
require('echarts/i18n/langEN');

// Initialize the chart on the server side
const chartHtml = echarts.renderToString({
  locale: 'EN',
  option: {
    title: { text: 'Server-side Rendered Chart' },
    series: [{ type: 'pie', data: [{ value: 335, name: 'A' }] }]
  }
});

Framework Integration Example

In frameworks like Vue or React, language switching can be implemented via state management. Here is a Vue 3 example:

<template>
  <div>
    <button @click="toggleLang">Toggle Language</button>
    <div ref="chartEl" style="width: 600px; height: 400px;"></div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import 'echarts/i18n/langEN';
import 'echarts/i18n/langZH';

export default {
  setup() {
    const chartEl = ref(null);
    const currentLang = ref('EN');
    let chartInstance = null;

    const initChart = () => {
      if (chartInstance) chartInstance.dispose();
      chartInstance = echarts.init(chartEl.value, null, { locale: currentLang.value });
      chartInstance.setOption({
        title: { text: currentLang.value === 'EN' ? 'Chart' : '图表' },
        series: [{ type: 'line', data: [10, 22, 28, 43, 49] }]
      });
    };

    const toggleLang = () => {
      currentLang.value = currentLang.value === 'EN' ? 'ZH' : 'EN';
    };

    onMounted(initChart);
    watch(currentLang, initChart);

    return { chartEl, toggleLang };
  }
};
</script>

Performance Optimization Recommendations

  1. Load Language Packs On-Demand: Use Webpack's code splitting feature to dynamically load language packs:

    const loadLang = async (lang) => {
      await import(`echarts/i18n/lang${lang}`);
      initChart(lang);
    };
    
  2. Cache Language Configurations: Avoid repeatedly registering loaded language packs:

    const loadedLocales = new Set();
    function registerLocale(lang) {
      if (!loadedLocales.has(lang)) {
        import(`echarts/i18n/lang${lang}`).then(() => {
          loadedLocales.add(lang);
        });
      }
    }
    
  3. Share Language Context: In large applications, share the current language via global state management:

    // Vuex/Pinia example
    store.subscribe((mutation) => {
      if (mutation.type === 'SET_LANGUAGE') {
        echarts.disposeAll();
        initCharts(mutation.payload);
      }
    });
    

Handling Complex Scenarios

For scenarios requiring mixed languages (e.g., bilingual reports), use callback functions to dynamically generate text:

chart.setOption({
  tooltip: {
    formatter: (params) => {
      return currentLang === 'EN' 
        ? `${params.seriesName}: ${params.value}`
        : `${params.seriesName}:${params.value}`;
    }
  }
});

Testing and Validation

Ensure the correctness of internationalization features with the following testing strategies:

  1. Visual Regression Testing: Use tools like BackstopJS to compare chart rendering results in different languages.
  2. Text Overflow Detection: Monitor container adaptation for languages with long text, such as German.
  3. Pseudo-Translation Testing: Replace all translated text with extended versions (e.g., "XxX_" prefix) to verify layout stability.
// Pseudo-translation example
const pseudoTranslate = (text) => `[${text}]`;
echarts.registerLocale('TEST', {
  title: { text: pseudoTranslate('Title') },
  legend: { data: [pseudoTranslate('Series1')] }
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:Vue3与GraphQL

下一篇:主题深度定制

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.