【问题标题】:Reloading partials Handlebars重新加载部分车把
【发布时间】:2013-06-28 17:41:00
【问题描述】:

我对编程很陌生,尤其是对车把。我在我的 html 文件中加载了一个 div,其中包含 jquery 和车把的组合。我在它上面有标签。单击选项卡时,我想将所有内容重新加载到新内容。内容相似(结构相同),但标签、图像等必须更改。我尝试在handlebars.js 中使用部分。 这是一个示例代码。

<script type="text/x-handlebars-template" id="all-handlebar">
    {{#each tabs}}
        <div id=tab{{@index}}>{{this.text}}</div>
    {{/each}}
    <div id="tab-content">{{> tabContentPartial}}
</script>
<script type="text/x-handlebars-template" id="tab-content-partial"> 
    <div id="mycontent">
        <div id="text">{{mycontent.text}}</div>
        <div id="text">{{mycontent.image}}</div>
    </div>      
</script>
<script type="text/javascript">
    source=$("#all-handlebar").html();
    var template = Handlebars.compile(source);
    Handlebars.registerPartial("tabContentPartial", $("#tab-content-partial").html())
    var context = {
        mycontent : {
            text="something that has to change everytime I click on a different tab",
            image="idem"
    };
    var html = template(context);
    $("body").html(html);
</script>

它第一次加载很好,但是当我单击选项卡时,我要求他重新注册选项卡内容部分脚本并且它不再存在,因为它已在我的代码中更改为 HTML 块。如何使用新内容重用和重新加载我的部分脚本?

非常感谢!

【问题讨论】:

  • 如果您提供一些相关代码会很有帮助。通常你通过你的编译你的车把模板。然后你传递你的数据,它返回你然后插入到你的页面的创建 html。这个编译后的模板可以重复使用不同的数据。
  • 现在清楚了吗?抱歉耽搁了,我尝试了不同的解决方案。

标签: jquery html handlebars.js partials


【解决方案1】:

您的代码中的选项卡切换部分丢失了,以及您如何检索数据,所以我只能告诉您在您收听选项卡切换的地方需要做什么

要实现这一点,你只需要编译你的#tab-content-partial,你不需要做太多的改变:

var source=$("#all-handlebar").html();
var contentSrc=$("#tab-content-partial").html();
var template = Handlebars.compile(source);
var contentTemplate = Handlebars.compile(contentSrc);

//because you already have a compiled version of your content template now you can pass this as partial
Handlebars.registerPartial("tabContentPartial", contentTemplate);
var context = {
    mycontent : {
        text : "something that has to change everytime I click on a different tab",
        image : "idem"
    }
 };

var html = template(context);
$("body").html(html);

然后在需要更改内容时,只需将内容的数据传递给内容模板,然后将#tab-content 的内容替换为新结果。 这样您还可以创建不同的内容模板。

//replace the content with the result of the template
$("#tab-content").html( contentTemplate(newContent) );

我希望这就是你要找的东西,如果不请自来。

【讨论】:

  • 这正是我想要的!非常感谢,它解决了我的问题。
  • 你能提供小提琴吗?
猜你喜欢
  • 2016-05-17
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多