SO?: Recursive jQuery Template with string array

SO?: http://stackoverflow.com/questions/7436189/how-do-i-prevent-jquery-template-from-digging-too-deeply-on-a-string-array-in-a-r

by Adam Patridge

HTML

<div class="results"></div>

<script id="reflectTemplate" type="text/x-jquery-tmpl"> 
    <ul>
        {{each(i, prop) $data}}
        {{if $data.hasOwnProperty(i)}}
        <li>
            ${i}:
            {{if $item.shouldDigDeeper(prop)}}
            {{tmpl(prop, { shouldDigDeeper: $item.shouldDigDeeper, formatDisplay: $item.formatDisplay }) "#reflectTemplate"}}
            {{else}}
            ${$item.formatDisplay(prop)}
            {{/if}}
        </li>
        {{/if}}
        {{/each}}
    </ul>
</script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

CSS

ul { border-left: 1px solid #aaa; margin-left: 15px; list-style-type: disc; }
ul ul { border-bottom: 1px solid #aaa; }
li li { margin-left: 5px; }
.type-string { color: #A31515; }
.type-string a, .type-string a:visited, .type-string a:hover { color: #A31515; }
.type-null,
.type-number { color: #281; }
.navigation { list-style-type: none; border: 1px solid #666; margin: 0 0 5px 0; }

JavaScript

$(function() {
    var data = {
        test1: 123,
        test2: { w: [ "some", "string", "array" ], x: 1, y: 2, z: "abc" },
        test3: [ "abc", "123", "def", "456" ],
        test4: null
    },
        templateFunctions = {
            shouldDigDeeper: function(itemToCheck) {
                return null !== itemToCheck && "object" === typeof(itemToCheck);
            },
            formatDisplay: function(propertyValue) {
                var propertyType = typeof (propertyValue),
                    result = propertyValue;

                if (null === result) {
                    result = "null";
                }
                else if ("string" === propertyType) {
                    result = "\"" + result + "\"";
                }
                return result;
            }
        };

    $("#reflectTemplate").tmpl(data, templateFunctions).appendTo($(".results"));
});