最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check whether object is empty in handlebars if statement? - Stack Overflow

programmeradmin5浏览0评论

In handlebars i need to check if an object is empty and if it isn't then i need to run a loop to grab the content from the object. Below is my code and a link to codepen. I imagine this is quite simple but nothing seems to work. I would have thought that the handlebars #if statement would see an empty object as undefined or 0 and ultimately the condition would be unfulfilled.

<div class="temp"></div>

<script id="temp" type="x-handlebars-template">
    {{#if tabs}}
    <p>true</p>
    {{/if}}
</script>

var template = Handlebarspile($("#temp").html());

var tabs = {};

var context = {
    tabs: tabs
}

$('.temp').html(template(context));

In handlebars i need to check if an object is empty and if it isn't then i need to run a loop to grab the content from the object. Below is my code and a link to codepen. I imagine this is quite simple but nothing seems to work. I would have thought that the handlebars #if statement would see an empty object as undefined or 0 and ultimately the condition would be unfulfilled.

<div class="temp"></div>

<script id="temp" type="x-handlebars-template">
    {{#if tabs}}
    <p>true</p>
    {{/if}}
</script>

var template = Handlebars.pile($("#temp").html());

var tabs = {};

var context = {
    tabs: tabs
}

$('.temp').html(template(context));

http://codepen.io/matt3224/pen/gaKyKv?editors=101

Share Improve this question asked Nov 1, 2015 at 15:35 mattpilottmattpilott 3561 gold badge6 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You can just use the built in handlebars each helper to acplish what you're looking for, and you can even conditionally render something with an empty object:

var template = Handlebars.pile($("#temp").html());

var tabs = {},
    test = {a: "Resources", b: "Contact"};

var context = {
    tabs: tabs,
    test: test
}

$('.temp').html(template(context));
<script src="//cdnjs.cloudflare./ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare./ajax/libs/handlebars.js/3.0.0/handlebars.min.js"></script>

<div class="temp"></div>

<script id="temp" type="x-handlebars-template">
    <h3>each helper on empty object</h3>
    {{#each tabs}}
        <p>Key: {{@key}} Value = {{this}}</p>
    {{else}}
        <p>Your tabs object is empty!</p>
    {{/each}}
    
    <h3>each helper on non-empty object</h3>
    {{#each test}}
        <p>Key: {{@key}} Value = {{this}}</p>
    {{else}}
        <p>Your test object is empty!</p>
    {{/each}}
</script>

发布评论

评论列表(0)

  1. 暂无评论