Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/guides/view_engines/handlebars.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ To enable [**handlebars**](https://handlebarsjs.com) support make use of the `vi

Handlebars is imported dynamically, so make sure to install it (`npm i hbs`). Otherwise `nestjs-i18n` can't register the helper function.

## Fastify

To use handlebars with fastify, `handlebars` is used instead of `hbs`. Make sure to install it (`npm i handlebars`).
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have already installed it as a dependency in package.json, so need to add this make sure to install at readme.


```diff title="src/app.module.ts"
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
},
+ viewEngine: 'handlebars'
})
```

:::

## Example usage
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"eslint-plugin-prettier": "^5.0.0",
"graphql-subscriptions": "^2.0.0",
"graphql-tag": "^2.12.6",
"handlebars": "^4.7.8",
"hbs": "^4.2.0",
"jest": "^29.7.0",
"pug": "^3.0.2",
Expand Down
14 changes: 11 additions & 3 deletions src/i18n.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,21 @@ export class I18nModule implements OnModuleInit, OnModuleDestroy, NestModule {
await this.i18n.refresh();

// Register handlebars helper
if (this.i18nOptions.viewEngine == 'hbs') {
if (
this.i18nOptions.viewEngine == 'hbs' ||
this.i18nOptions.viewEngine == 'handlebars'
) {
try {
const hbs = await import('hbs');
// Import handlebars or hbs
const hbs =
this.i18nOptions.viewEngine === 'hbs'
? await import('hbs')
: await import('handlebars');

hbs.registerHelper('t', this.i18n.hbsHelper);
logger.log('Handlebars helper registered');
} catch (e) {
logger.error('hbs module failed to load', e);
logger.error(this.i18nOptions.viewEngine + ' module failed to load', e);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/i18n-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export interface I18nOptions {
loaderOptions: any;
formatter?: Formatter;
logging?: boolean;
viewEngine?: 'hbs' | 'pug' | 'ejs';
viewEngine?: 'hbs' | 'handlebars' | 'pug' | 'ejs';
disableMiddleware?: boolean;
skipAsyncHook?: boolean;
validatorOptions?: I18nValidatorOptions;
Expand Down
103 changes: 103 additions & 0 deletions tests/i18n-handlebars.e2e.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Test } from '@nestjs/testing';
import * as path from 'path';
import {
CookieResolver,
HeaderResolver,
AcceptLanguageResolver,
I18nModule,
QueryResolver,
I18nJsonLoader,
} from '../src';
import * as request from 'supertest';
import { HelloController } from './app/controllers/hello.controller';
import { NestFastifyApplication } from '@nestjs/platform-fastify';
import { join } from 'path';
import { Global, Module } from '@nestjs/common';

@Global()
@Module({
providers: [
{
provide: 'OPTIONS',
useValue: ['lang', 'locale', 'l'],
},
],
exports: ['OPTIONS'],
})
export class OptionsModule {}

describe('i18n module e2e handlebars', () => {
let app: NestFastifyApplication;

beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [
OptionsModule,
I18nModule.forRoot({
fallbackLanguage: 'en',
fallbacks: {
'en-CA': 'fr',
'en-*': 'en',
'fr-*': 'fr',
fr: 'fr-FR',
pt: 'pt-BR',
},
resolvers: [
{
use: QueryResolver,
useFactory: (options) => {
return options;
},
inject: ['OPTIONS'],
},
new HeaderResolver(['x-custom-lang']),
new CookieResolver(),
AcceptLanguageResolver,
],
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
},
viewEngine: 'handlebars',
}),
],
controllers: [HelloController],
}).compile();

app = module.createNestApplication<NestFastifyApplication>();

app.setViewEngine({
engine: {
handlebars: require('handlebars'),
},
templates: join(__dirname, 'app', 'views/hbs'),
});

await app.init();
});

it(`should render translated page`, async () => {
await request(app.getHttpServer())
.get('/hello/index')
.expect(200)
.expect('Every day');

await request(app.getHttpServer())
.get('/hello/index?l=nl')
.expect(200)
.expect('Iedere dag');

await request(app.getHttpServer())
.get('/hello/index2')
.expect(200)
.expect('Hello');

return request(app.getHttpServer())
.get('/hello/index2?l=nl')
.expect(200)
.expect('Hallo');
});

afterAll(async () => {
await app.close();
});
});