简体   繁体   中英

Transforming tree structure using Tempo

I have started on using JSON data structures instead of XML in a little Web project. I need to do some transformation of the data, like you normally do with XSLT on XML, and then I stumpled upon the cool library http://tempojs.com .

But the real problem appeared when I realized, that my data is a tree structure and I guess some recursion in the transformation is needed.

Here's a sample of the data structure:

[
        {
            "text" : "The sun is shining",
            "children" : []
        },
        {
            "text" : "it's cloudy.",
            "children" :  
            [
                {   
                    "text" : "It's raining.",
                    "children" : []
                },
                {
                    "text" : "The sun was shining.",
                    "children" : []
                },
                {
                    "text" : "A rainbow appeared.",
                    "children" : 
                    [
                        {   
                            "text" : "A pot of gold was found at the end of the rainbow.",
                            "children" : []
                        },
                        {
                            "text" : "The gold returned more than a million dollars, when sold.",
                            "children" : []
                        }
                    ]
                }
            ]
        }
    ]

And that I would like to transform into a nested HTML list like this:

<ul>
    <li>The sun is shining</li>
    <li>it's cloudy.
        <ul>
            <li>It's raining.</li>
            <li>The sun was shining.</li>
            <li>A rainbow appeared.
                <ul>
                    <li>A pot of gold was found at the end of the rainbow.</li>
                    <li>The gold returned more than a million dollars, when sold.</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Any Ideas how this could be done using Tempo?

Tempo 1.x could not handle multiple levels of nested templates. However, the 2.0-dev branch supports this and seems to me to render your data correctly: http://jsfiddle.net/mr_olafsson/wLEQs/

Note, that the example does imply a fixed (and equal) number of levels/nested templates. Let me know how you get on! Sorry for the late reply.

I dont know tempo, I use underscore.js instead.

it will be something like this:

var mytemplate = "
<%= text %>
<ul>
    <% _.each(children, function(child){ %>
    <li><%= child.text %></li>
    <li><%= _.template(mytemplate, child.children) %>
    </li>
</ul>
";

var htmlResult = _.template(mytemplate, myJSON);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM