简体   繁体   English

如何在Handlebars.js中的表达式中存储模板?

[英]How to store a template in an expression in Handlebars.js?

I want to place my templates on several places in the DOM without having to write the jQuery expression over and over again. 我想将模板放在DOM中的多个位置上,而不必一遍又一遍地编写jQuery表达式。 I want to place my template in the DOM by just typing the variable/attribute {{template}} anywhere in the body. 我想通过在正文中的任意位置键入变量/属性{{template}}来将模板放置在DOM中。

Is this doable using Handlebars? 使用车把是否可行? If not, is there any other way for me to achieve this? 如果没有,我还有其他方法可以实现这一目标吗?

You need to use HandleBar helpers 您需要使用HandleBar助手

handlebar_helpers handlebar_helpers
ps dont forget to use safestring else it will be escaped by default ps别忘了使用safestring,否则默认情况下会被转义



Updating with answer based on ur comment The link i provided did give out an excellent explanation. 根据您的评论更新答案我提供的链接确实给出了很好的解释。 However please find below an example. 但是,请在下面找到一个示例。
Assume your need to return a welcome message when a name is given 假设您需要给定名字时返回欢迎消息

Handlebars.registerHelper('welcome', function(name) {
  return new Handlebars.SafeString(
    "<p>Hi "+name+", welcome to stackoverflow</p>"
  );
});

Then calling {{{welcome "sagittarius"}}} will return 然后致电{{{welcome "sagittarius"}}}将返回

Hi sagittarius, welcome to stackoverflow 嗨,射手座,欢迎来到stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM