【问题标题】:Is there a way to use i18n in .pug files in Angular 2有没有办法在 Angular 2 的 .pug 文件中使用 i18n
【发布时间】:2016-10-12 12:38:00
【问题描述】:

我尝试在 .pug 文件中的 Angular 2 项目中添加 i18n。 “./node_modules/.bin/ng-xi18n”命令失败,并显示“无法从“..\index.ts”解析模块@angular/core/src/di/metadata。有没有办法使用 i18n 本地化和 .pug 或 html 是目前唯一的解决方案?谢谢。

【问题讨论】:

    标签: angular internationalization pug


    【解决方案1】:

    是的,使用 angular/cli + ngx-translate + pug-cli 就可以了。

    首先,设置您的 TranslationConfigModule。创建一个名为 translation.config.module.ts 的新模块

    import { HttpModule, Http } from '@angular/http';
    import { NgModule, ModuleWithProviders } from '@angular/core';
    import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    
    export function HttpLoaderFactory(http: Http) {
        return new TranslateHttpLoader(http, '../../../assets/i18n/', '.json');
    }
    
    const translationOptions = {
        loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [Http]
        }
    };    
    
    @NgModule({
        imports: [TranslateModule.forRoot(translationOptions)],
        exports: [TranslateModule],
        providers: [TranslateService]
    })
    export class TranslationConfigModule {
    
       /**
         * @param translate {TranslateService}
         */
         constructor(private translate: TranslateService) {
            // Setting up Translations
            translate.addLangs(['en', 'it']);
            translate.setDefaultLang('en');
            const browserLang = translate.getBrowserLang();
            // English and Italian, just an example
            translate.use(browserLang.match(/en|it/) ? browserLang : 'it');
        }
    }
    

    然后,将其导入您想要的任何模块中,例如app.module.ts

    . . . 
    
    import { TranslationConfigModule } from '../shared/modules/translation.config.module';
    
    . . . 
    
    @NgModule({
        declarations: [ ],
        imports: [
            TranslationConfigModule
        ],
        exports: [ ]
    })
    

    现在,您需要在myapp/src/assets/i18n 中构建一些i18n.jsons。 例如。 en.json 将包含:

    {
        "TEST" : {
            "TITLE" : "Herro Pug!"
        }
    }
    

    现在按照我的这个答案Use Jade as angular2 template engine 的步骤设置哈巴狗集成。

    现在使用 i18n 享受您的哈巴狗模板。当然,您只能在要导入此模块的模块中声明和导出的组件上使用此翻译模块。

    test.pug

    h3 {{ 'TEST.TITLE' | translate }}
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2016-12-06
      • 2017-08-26
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2014-12-03
      • 1970-01-01
      相关资源
      最近更新 更多