eggjs / egg

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa
https://eggjs.org
MIT License
18.88k stars 1.81k forks source link

Adding new function to Nunjucks #4807

Open sm2017 opened 2 years ago

sm2017 commented 2 years ago

In documentation we have

<li>{{ __('Email') }}: {{ user.email }}</li>
<li>
  {{ __('Welcome back, %s!', user.name) }}
</li>
<li>
  {{ __('Hello {0}! My name is {1}.', ['foo', 'bar']) }}
</li>

I want to know how you add __ to the Nunjucks, I need to add a t function for my localizations Can you please show me the source code?

fengmk2 commented 2 years ago

@sm2017 hello, you can set a t alias function to __ like gettext does.

app.context.t = app.context.__;
sm2017 commented 2 years ago

@fengmk2 I read the source codes, but cannot find where you defined app.context.__ in the Nunjucks, can you please show me the code?

fengmk2 commented 2 years ago

@sm2017 egg will set __ function to ctx.locals then merge all locals on view plugin before pass to nunjucks engine.

sm2017 commented 2 years ago

@fengmk2 thanks a lot

sm2017 commented 2 years ago

@sm2017 hello, you can set a t alias function to __ like gettext does.

app.context.t = app.context.__;

The t function is the i18next.t function, So I don't want to override it

Is it safe to use the following code?

ctx.locals.t = t
sm2017 commented 2 years ago

@fengmk2 @atian25 Can you please reply ? is it safe to override ctx.locals.t = t?

sm2017 commented 2 years ago

@fengmk2 I need your help!