需要Handlebarsjs的帮助,模板无法正常工作/渲染

时间:2020-08-13 14:56:07

标签: javascript html jquery handlebars.js

在为我自己测试Handlebarsjs之前,我在YouTube上搜索了一些教程并进行了观看。因此,基本上我遵循了视频中显示的示例,尽管由于某种原因我的视频无法正常工作。

下面是我的html文件(也是模板的容器)中的模板脚本。

<div id="recents">
   <div id="recents-template-container" class="grid-container">
                    
   </div>
</div>

<script id="recents-template" type="text/x-handlebars-template">
    {{#each jobposts}}
        <div id="box-{{@key}}" class="recents-box flex-container">
            <div class="box-row">
                <span id="jobtitle">{{jobtitle}}</span>
            </div>
            <div class="box-row">
                <span id="company">{{company}}</span>
            </div>
            <div class="box-row">
                <span id="year">{{experience.year}}</span>
                <span id="months">{{experience.months}}</span>
            </div>
            <div class="box-row">
                <span id="location">{{location}}</span>
            </div>
        </div>
    {{/each}}
</script>

<script type="module" src="src/js/index.js"></script>

注意:这两个在body标签的末尾。 下面是我的index.js文件

//index.js
import {recents} from "./query.js";
recents();

和query.js

//query.js
export function recents(){
const date = new Date();
const isoDate = `${date.getFullYear()}-0${(date.getMonth()+1)}-${date.getDate()}`;
const url = `http://localhost:3000/jobposts?dateposted_like=${isoDate}&_limit=5`;

$(document).ready(function() {
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(data){
            console.log(data);

            createRecents(data);
        }, 
        error: function(data){
            console.error(data);
        }
    });


    function createRecents(data){
        const template = $("#recents-template").html();
        const compiledTemplate = Handlebars.compile(template);
        const html = compiledTemplate(data);
        
        $("#recents-template-container").html(html);
    }
});
}

我还在Handlebarjs的网站上尝试了该模板,并且效果很好。我的实现方式或编码方式有问题吗?

P.S。抱歉,我的代码看起来不好。

0 个答案:

没有答案
相关问题