跟着JHipster学做项目 (18) 国际化i18n实现

17 篇文章 0 订阅
16 篇文章 1 订阅

通过添加i18n功能,改变的(包括新增)文件如下:

package.json
src/main/docker/jhipster-control-center.yml
src/main/java/com/adun/api/web/rest/errors/ExceptionTranslator.java
src/main/java/com/adun/api/web/rest/UserResource.java
src/main/resources/config/application-dev.yml
src/main/resources/config/application-prod.yml
src/main/webapp/app/account/account.service.ts
src/main/webapp/app/account/activate/activate.vue
src/main/webapp/app/account/change-password/change-password.vue
src/main/webapp/app/account/login-form/login-form.vue
src/main/webapp/app/account/register/register.component.ts
src/main/webapp/app/account/register/register.vue
src/main/webapp/app/account/reset-password/finish/reset-password-finish.vue
src/main/webapp/app/account/reset-password/init/reset-password-init.vue
src/main/webapp/app/account/settings/settings.vue
src/main/webapp/app/admin/configuration/configuration.vue
src/main/webapp/app/admin/health/health-modal.vue
src/main/webapp/app/admin/health/health.vue
src/main/webapp/app/admin/logs/logs.vue
src/main/webapp/app/admin/metrics/metrics-modal.vue
src/main/webapp/app/admin/metrics/metrics.vue
src/main/webapp/app/admin/user-management/user-management-edit.component.ts
src/main/webapp/app/admin/user-management/user-management-edit.vue
src/main/webapp/app/admin/user-management/user-management-view.vue
src/main/webapp/app/admin/user-management/user-management.component.ts
src/main/webapp/app/admin/user-management/user-management.vue
src/main/webapp/app/app.vue
src/main/webapp/app/core/error/error.vue
src/main/webapp/app/core/home/home.vue
src/main/webapp/app/core/jhi-footer/jhi-footer.vue
src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.ts
src/main/webapp/app/core/jhi-navbar/jhi-navbar.vue
src/main/webapp/app/core/ribbon/ribbon.vue
src/main/webapp/app/declarations.d.ts
src/main/webapp/app/main.ts
src/main/webapp/app/shared/alert/alert.service.ts
src/main/webapp/app/shared/config/config.ts
src/main/webapp/app/shared/config/dayjs.ts
src/main/webapp/app/shared/jhi-item-count.component.ts
src/main/webapp/app/shared/jhi-item-count.vue
src/main/webapp/index.html
src/test/resources/config/application.yml
src/test/resources/i18n/messages_en.properties
webpack/webpack.common.js
src/main/resources/i18n/messages_en.properties
src/main/resources/i18n/messages_zh_CN.properties
src/main/resources/i18n/messages_zh_TW.properties
src/main/webapp/app/locale
src/main/webapp/app/locale/translation.service.ts
src/main/webapp/app/shared/config/formatter.ts
src/main/webapp/app/shared/config/store/translation-store.ts
src/main/webapp/i18n
src/main/webapp/i18n/en
src/main/webapp/i18n/en/activate.json
src/main/webapp/i18n/en/configuration.json
src/main/webapp/i18n/en/error.json
src/main/webapp/i18n/en/global.json
src/main/webapp/i18n/en/health.json
src/main/webapp/i18n/en/home.json
src/main/webapp/i18n/en/login.json
src/main/webapp/i18n/en/logs.json
src/main/webapp/i18n/en/metrics.json
src/main/webapp/i18n/en/password.json
src/main/webapp/i18n/en/register.json
src/main/webapp/i18n/en/reset.json
src/main/webapp/i18n/en/sessions.json
src/main/webapp/i18n/en/settings.json
src/main/webapp/i18n/en/user-management.json
src/main/webapp/i18n/zh-cn
src/main/webapp/i18n/zh-cn/activate.json
src/main/webapp/i18n/zh-cn/configuration.json
src/main/webapp/i18n/zh-cn/error.json
src/main/webapp/i18n/zh-cn/global.json
src/main/webapp/i18n/zh-cn/health.json
src/main/webapp/i18n/zh-cn/home.json
src/main/webapp/i18n/zh-cn/login.json
src/main/webapp/i18n/zh-cn/logs.json
src/main/webapp/i18n/zh-cn/metrics.json
src/main/webapp/i18n/zh-cn/password.json
src/main/webapp/i18n/zh-cn/register.json
src/main/webapp/i18n/zh-cn/reset.json
src/main/webapp/i18n/zh-cn/sessions.json
src/main/webapp/i18n/zh-cn/settings.json
src/main/webapp/i18n/zh-cn/user-management.json

1  package.json: 增加了两个packages, Folder-hash和merge-jsons-webpack-plugin

Folder-hash: 为文件夹添加hashcode, 确保显示最新的多语言信息;

merge-jsons-webpack-plugin: 将分散的json组合为一个文件

2  ExceptionTranslator.java: 设置createFailureAlert方法中的参数enableTranslation为true.

    @ExceptionHandler
    public ResponseEntity<Problem> handleEmailAlreadyUsedException(
        com.adun.api.service.EmailAlreadyUsedException ex,
        NativeWebRequest request
    ) {
        EmailAlreadyUsedException problem = new EmailAlreadyUsedException();
        return create(
            problem,
            request,
            HeaderUtil.createFailureAlert(applicationName, true, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())
        );
    }

3 UserResource.java: 设置createAlert方法中的参数message为error key.

    public ResponseEntity<Void> deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
        log.debug("REST request to delete User: {}", login);
        userService.deleteUser(login);
        return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, "userManagement.deleted", login)).build();
    }

4 account.service.ts 添加当前语言类型设置和页面翻译

if (this.store.getters.currentLanguage !== account.langKey) {
    this.store.commit('currentLanguage', account.langKey);
}

this.translationService.refreshTranslation(this.store.getters.currentLanguage);

5 activate.vue 添加多语言信息

        <h1 v-text="$t('activate.title')">Activation</h1>
        <div class="alert alert-success" v-if="success">
          <span v-html="$t('activate.messages.success')"><strong>Your user account has been activated.</strong> Please </span>
          <a class="alert-link" v-on:click="openLogin" v-text="$t('global.messages.info.authenticated.link')">sign in</a>.
        </div>
        <div class="alert alert-danger" v-if="error" v-html="$t('activate.messages.error')">

6 index.html 阻止页面自动翻译

<meta name="google" content="notranslate" />

7 main.ts 添加翻译模块

import TranslationService from '@/locale/translation.service';

const i18n = config.initI18N(Vue);

const translationService = new TranslationService(store, i18n);
const loginService = new LoginService();
const accountService = new AccountService(store, translationService, router);

8 config.ts 添加initI18N

export function initI18N(vue) {
  vue.use(VueI18n);
  return new VueI18n({
    dateTimeFormats,
    silentTranslationWarn: true,
    formatter: new JhiFormatter(),
  });
}

9 webpack.common.js 添加folder-hash和MergeJsonWebpackPlugin

const { hashElement } = require('folder-hash');
const MergeJsonWebpackPlugin = require('merge-jsons-webpack-plugin');

  const languagesHash = await hashElement(resolve('src/main/webapp/i18n'), {
    algo: 'md5',
    encoding: 'hex',
    files: { include: ['*.json'] },
  });

        new MergeJsonWebpackPlugin({
          output: {
            groupBy: [
              { pattern: './src/main/webapp/i18n/en/*.json', fileName: './i18n/en.json' },
              { pattern: './src/main/webapp/i18n/zh-cn/*.json', fileName: './i18n/zh-cn.json' },
              { pattern: './src/main/webapp/i18n/zh-tw/*.json', fileName: './i18n/zh-tw.json' },
              // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
            ],
          },

10 增加translation-store.ts, translation.service.ts, 以及对应的json信息文件。

最后,但是很重要的一点总结,JHipster国际化的思路是把所有的翻译工作放在前端来完成,利用vue-i18n,后端只有在发送邮件时会根据用户的langKey来获取信息,代码如下:

    @Async
    public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
        if (user.getEmail() == null) {
            log.debug("Email doesn't exist for user '{}'", user.getLogin());
            return;
        }
        Locale locale = Locale.forLanguageTag(user.getLangKey());
        Context context = new Context(locale);
        context.setVariable(USER, user);
        context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
        String content = templateEngine.process(templateName, context);
        String subject = messageSource.getMessage(titleKey, null, locale);
        sendEmail(user.getEmail(), subject, content, false, true);
    }

Good Luck,

Cheers!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值