jsViews checking length returns error


I am using jSViews and getting data back via JSON and then linking to the template.

The template shows the data I am sending it, however I have a simple post template with an array of comments.

If I try and check that the length of the array is greater than 0, using lenth, it crashed with:

0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference

here is a snippet of code:

.done(function (json) {
    posts_data = json;

    if (posts_data) {
       if (posts_data.length > 0) {                      
            var posts_html = $("#posts-template").render(posts_data);
            $(".posts .row").html(posts_html);

            $.templates("#post-detail-template").link(".single-post-detail .row", post_detail); // post_detail is initially an empty object


$(".post").on("click", "#posts-section", function (event) {
    // get the index of the clicked item - should be able to do this with $.view but it isnt working - check it out.
    var idx = $(this).closest(".dashboard-post").attr("data-index");

    // update it observably so we dont have to traverse the DOM.


script id="post-detail-template" type="text/x-jsrender">
<div class="col s12 m12 l6 post">
            {^{if comments.length > 0}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:

script id="post-detail-comments-template" type="text/x-jsrender">
<section class="comments-section">
    <ul class="comments-list">
        {^{for #data}}
        <li class="comment-item">

I can hack it using a helper:

{^{if ~hasLength(comments)}}
                {^{include comments tmpl="#post-detail-comments-template"/}}:

var viewHelpers = {
    hasLength: function (arr) {
        if (!arr) { return false; }

        var x = arr;
        if (x.length > 0) {
            return true;
        return false;



however I cant understand why it is giving me this error as ideally, I just want to include the comments template IF there are comments and not have to use an if at all, but this is the only way I can get it to work

asked on Stack Overflow Mar 30, 2017 by grayson

1 Answer


If the post_detail has no comments property then {^{if comments.length}} will indeed produce an error. If you include a 'null check' it should work:

{^{if comments && comments.length > 0}}...{{/if}}
answered on Stack Overflow Mar 30, 2017 by BorisMoore

User contributions licensed under CC BY-SA 3.0