[英]Handlebars helpers as tags
我使用正则表达式将字符串中的**text in bold**
替换为<strong>text in bold</strong>
,然后在我的EmberJS模板上使用{{{message}}}
显示message
。 问题是我也想用{{#link-to "hashtag" "anyhashtag"}}
替换#anyhashtag
,并且仅适用于{{message}}
。
所以我的想法是创建一个{{strong}}text in bold{{/strong}}
助手,它也将更加安全,但是显然,助手只能像{{strong "text in bold"}}
工作,如果我的链接使用粗体或更复杂的字符串。
我可以做一个像我的想法一样的助手吗?
谢谢!
这个问题有点令人困惑,但是我认为这是您要的:
Ember.Handlebars.registerHelper("strong", function (options) {
options.hash.layout = Ember.Handlebars.compile("<strong>{{yield}}</strong>");
return Ember.Handlebars.helpers.view.call(this, Ember.View, options);
});
工作演示 。
实际上,一个更好的变体是这样的:
Ember.Handlebars.registerHelper("strong", function (options) {
options.hash.tagName = "strong";
return Ember.Handlebars.helpers.view.call(this, Ember.View, options);
});
这样可以避免将<strong>
包装到<div>
。 如果需要更复杂的包装器,则第一个版本将很有用。 更新了演示 。
似乎您正在尝试根据用户提供的内容创建动态模板。 您无法通过将模板字符串插入{{{}}}
构造中来做到这一点。 “ Triple-mustache”用于原始html输出,它无法处理其中的其他模板代码。
不幸的是,您也不能直接通过属性对其进行编译。 Handlebars编译器实际上是在生成一个函数,然后需要使用一堆与Ember相关的上下文东西来调用该函数以生成html。
(我所知道的)解决所有问题的最好方法是再次通过视图。 像这样:
App.ApplicationController = Ember.Controller.extend({
text: "text in bold",
html: function() {
return Ember.Handlebars.compile("{{#strong}}" + this.get('text') + "{{/strong}}");
}.property("text")
});
<script type="text/x-handlebars">
<div>Working: {{#strong}}text in bold{{/strong}}</div>
<div>Working: {{view Ember.View template=html tagName="span"}}</div>
</script>
这将显示正确的值,但是如果您更改它,则不会更新。 要获取实时更新,请执行以下操作:
App.UpdatableView = Ember.View.extend({
templateChanged: function () {
this.rerender();
}.observes("template")
});
<script type="text/x-handlebars">
<div>Working: {{#strong}}text in bold{{/strong}}</div>
<div>Working: {{view App.UpdatableView templateBinding=html tagName="span"}}</div>
<!-- Type here to see changes -->
{{input type="text" value=text}}
</script>
在此处更新了现场演示。
更新:当然,既然我已经了解了您要做什么,我知道您真的不需要{{strong}}
助手的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.