Stanley
Stanley

Reputation: 5127

How to render property name of JSON object with JsRender?

I have a JSON object with dynamic property name. How can I render the property name with JsRender? I have been looking at the samples from JsRender demo page but couldn't find a way to do so.

Example:

{
    'prop1': '123',
    'prop2': '456'
}

Expected output:

1. prop1 = 123
2. prop3 = 456

JsFiddle: http://jsfiddle.net/kvuZC/

UPDATE Working JsFiddle: http://jsfiddle.net/B76WP/

Upvotes: 3

Views: 4088

Answers (3)

Alex
Alex

Reputation: 1260

check the {{props}} tag, it is very useful to solve this question. https://www.jsviews.com/#propstag

{{props}}
    1. {{>key}} = {{>prop}}
{{/props}}

and the output will be the desired.

Upvotes: 3

Sergii
Sergii

Reputation: 1320

You can iterate through field with helper

$.views.helpers({
    getFields: function( object ) {
        var key, value,
            fieldsArray = [];
        for ( key in object ) {
            if ( object.hasOwnProperty( key )) {
                value = object[ key ];
                // For each property/field add an object to the array, with key and value
                fieldsArray.push({
                    key: key,
                    value: value
                });
            }
        }
        // Return the array, to be rendered using {{for ~fields(object)}}
        return fieldsArray;
    }
});

Code from 'Iterating through fields' scenario

{{for ~getFields(details)}}
   <b>{{>key}}</b>: {{>value}}
{{/for}}

Upvotes: 3

dugokontov
dugokontov

Reputation: 4612

Change approach. Map your object in array of objects that will hold your key and value.

This is code that should do that:

var jsonData = {
    'prop1': '123',
    'prop2': '456'
}
, data = $.map(jsonData, function(value, key) {return {value: value, key: key}});

$('#container').html($('#dynamicObjectTemplate').render(data));

This will create following:

[{
  value: '123',
  key: 'prop1'
},{
  value: '456',
  key: 'prop2'
}]

And here is working example on jsfiddle (Couldn't include jsrender code via reference, so I pasted it... your code is at the bottom)

Upvotes: 2

Related Questions