gpt4 book ai didi

javascript - 作为标签的 Handlebars 助手

转载 作者:行者123 更新时间:2023-11-30 17:31:27 28 4
gpt4 key购买 nike

使用正则表达式,我正在替换 **text in bold**<strong>text in bold</strong>在一个字符串中,然后显示 message使用 {{{message}}}在我的 EmberJS 模板上。问题是我也想更换 #anyhashtag{{#link-to "hashtag" "anyhashtag"}}它只适用于 {{message}} .

所以我的想法是创建一个 {{strong}}text in bold{{/strong}} helper 也更安全,但显然 helpers 只能像 {{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);
});

工作 demo .


实际上,更好的变体是这样的:

Ember.Handlebars.registerHelper("strong", function (options) {
options.hash.tagName = "strong";
return Ember.Handlebars.helpers.view.call(this, Ember.View, options);
});

这避免了包装 <strong>进入<div> .如果您需要更复杂的包装器,第一个版本会很有用。更新 demo .


您似乎正在尝试根据用户提供的内容创建动态模板。您不能通过将模板字符串插入 {{{}}} 来做到这一点构造。 'Triple-mustache' 用于原始 html 输出,它没有处理其中额外模板代码的能力。

不幸的是,你也不能通过属性直接编译它。 Handlebars 编译器实际上正在生成一个函数,然后需要使用一堆与 Ember 相关的上下文内容来调用该函数以生成 html。

再一次,解决所有这些问题的最佳方法(据我所知)是通过 View 。像这样:

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>

更新现场演示 here .

更新:当然,既然我明白了你想做什么,我意识到你并不真的需要答案的第一部分,即 {{strong}}。 helper 。

关于javascript - 作为标签的 Handlebars 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22992098/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com