如何在Handlebars中通过布局模板向嵌套局部传递语言参数?
向Handlebars所有局部模板传递配置参数的简便方法
针对你的需求(通过布局模板设置语言,让所有嵌套局部模板自动访问该参数),有几种实用的实现方式,以下是具体方案:
方法一:利用上下文继承传递语言参数
通过{{#with}}块在布局模板中封装包含lang的上下文,所有嵌套的局部模板会自动继承这个上下文,无需手动传递参数。
步骤1:修改语言布局模板
@layout-en.hbs:
{{#*inline "@layout-en"}} {{#with (hash lang="en" title=title)}} <!DOCTYPE html> <html lang="{{lang}}"> <head> <title>{{title}}</title> </head> <body> <p>Top of all English pages</p> {{{content}}} <p>Footer of all English pages</p> </body> </html> {{/with}} {{/inline}}
@layout-fr.hbs(同理):
{{#*inline "@layout-fr"}} {{#with (hash lang="fr" title=title)}} <!DOCTYPE html> <html lang="{{lang}}"> <head> <title>{{title}}</title> </head> <body> <p>Haut de toutes les pages françaises</p> {{{content}}} <p>Pied de page de toutes les pages françaises</p> </body> </html> {{/with}} {{/inline}}
步骤2:在局部模板中直接使用lang参数
demo.hbs:
{{!-- 需先注册eq helper用于判断 --}} {{#if (eq lang "en")}} <button>Submit</button> {{else if (eq lang "fr")}} <button>Envoyer</button> {{/if}}
注册eq helper的JS代码:
Handlebars.registerHelper('eq', function(a, b) { return a === b; });
方法二:使用全局Root上下文传递
如果不想用{{#with}}块,可以将lang参数设置到Handlebars的全局@root上下文中,所有模板都能直接访问。
修改布局模板
@layout-en.hbs:
{{#*inline "@layout-en"}} {{!-- 将lang写入全局root --}} {{@root.lang = "en"}} <!DOCTYPE html> <html lang="{{@root.lang}}"> <head> <title>{{title}}</title> </head> <body> <p>Top of all English pages</p> {{{content}}} <p>Footer of all English pages</p> </body> </html> {{/inline}}
局部模板中访问全局lang
demo.hbs:
{{#if (eq @root.lang "en")}} <button>Submit</button> {{else if (eq @root.lang "fr")}} <button>Envoyer</button> {{/if}}
更优方案:使用国际化(i18n)Helper管理多语言文本
如果你的项目涉及大量多语言内容,推荐用集中式的语言文件管理文本,避免在模板中写大量条件判断,扩展性更强。
步骤1:创建语言配置文件
en.json:
{ "button.submit": "Submit", "page.top": "Top of all English pages", "page.footer": "Footer of all English pages" }
fr.json:
{ "button.submit": "Envoyer", "page.top": "Haut de toutes les pages françaises", "page.footer": "Pied de page de toutes les pages françaises" }
步骤2:注册i18n Helper
// 导入语言文件 const translations = { en: require('./en.json'), fr: require('./fr.json') }; // 注册翻译Helper Handlebars.registerHelper('t', function(key) { // 优先取当前上下文的lang,没有则用全局root的lang,默认英文 const lang = this.lang || this.root?.lang || 'en'; return translations[lang][key] || key; });
步骤3:修改布局模板
@layout-en.hbs:
{{#*inline "@layout-en"}} {{#with (hash lang="en" title=title)}} <!DOCTYPE html> <html lang="{{lang}}"> <head> <title>{{title}}</title> </head> <body> <p>{{t "page.top"}}</p> {{{content}}} <p>{{t "page.footer"}}</p> </body> </html> {{/with}} {{/inline}}
步骤4:简化局部模板
demo.hbs:
<button>{{t "button.submit"}}</button>
这种方式下,新增语言只需添加对应的json文件,模板无需修改,维护成本更低。
内容的提问来源于stack exchange,提问作者Jirka
相关产品推荐
相关产品推荐

