繁体   English   中英

具有handlebars.js的多个模板

[英]multiple templates with handlebars.js

我是javascript和库的新手,所以这可能是一个简单的问题。 我正在尝试使用handlebars.js模板引擎和jQuery制作几个简单的网页。 我一直遇到的问题是制作多个页面。 到目前为止,我的主页有不同的名称。 每个名称上都有一个jquery click功能。 如果单击名称,则仅使用jQuery更改当前页面。 因此,基本上,如果您单击一个名称,则会得到一个新模板,其中包含该人的图片列表,但在同一页面上请说index.html。 这样做的问题是,如果您想返回第一个视图,则“后退”按钮现在不起作用。 我的结构是否正确? 链接应该发送到另一个页面和另一个模板吗? 如果是这样,我如何根据所按的链接生成模板。

$(document).ready(function(){


var source = $(".some-template").html();
var template = Handlebars.compile(source);

data = { date: "today", firstUsers: [
{firstName: "person1", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person2", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person3", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person4", pictures: ["pic1", "pic2", "pic3"]},
]
};
$(".container").html(template(data))

$("li").click(function(){
    var name = $(this).html()
    $.each(data.firstUsers, function(i, item){
        if(name === item.firstName){
            y = item.pictures
            return y
        };//if function
    });//each function


    $(".container").hide()
    var source = $(".some-script").html();
    var template = Handlebars.compile(source);
    datas = {namer: name, pictures: y,}
    //console.log(datas.pictures)
    $(".content").html(template(datas))
});//click function
});//document ready

使用最佳做法,您可能应该将URL与每个页面相关联。 如果使用window.history.pushState ,则有一种相当简单的方法来使后退/前进按钮正常工作。

因此,基本上它的工作方式如下:

  1. 每次加载新模板时,请推入新的浏览器状态。
  2. 监听onpopstate事件,并在触发时加载适当的模板。

为了实现可重用性,我将上述函数分为两个单独的函数:

function loadUser(name) {
    var y;
    $.each(data.firstUsers, function(i, item){
        if(name === item.firstName){
            y = item.pictures
            return y
        };//if function
    });//each function

    $(".container").hide()
    var source = $(".some-script").html();
    var template = Handlebars.compile(source);
    datas = {namer: name, pictures: y,}
    //console.log(datas.pictures)
    $(".content").html(template(datas))
    window.history.pushState(null, null, name);
}

// Find the name of the user
// TODO: change the regex to match your URL scheme
function popStateResponder() {
    var name = window.location.pathname.match(/\w+$/)[0];
    loadUser(name);
}

$("li").click(function(){
    var name = $(this).html(),

    loadUser(name);
});//click function

$(window).on('popstate', popStateResponder);

可能需要更改一些内容,但这是我通常用于此类任务的常规工作流程。

暂无
暂无

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

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