Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render property name of JSON object with JsRender?

Tags:

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/

like image 928
Stanley Avatar asked Nov 21 '25 15:11

Stanley


2 Answers

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}}
like image 128
Sergii Avatar answered Nov 24 '25 08:11

Sergii


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.

like image 28
Alex Avatar answered Nov 24 '25 08:11

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!