2

我已经开始在一个小型 Web 项目中使用 JSON 数据结构而不是 XML。我需要对数据进行一些转换,就像您通常在 XML 上使用 XSLT 所做的那样,然后我偶然发现了很酷的库http://tempojs.com

但是当我意识到我的数据是一个树形结构时,真正的问题出现了,我想在转换中需要一些递归。

这是数据结构的示例:

[
        {
            "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" : []
                        }
                    ]
                }
            ]
        }
    ]

我想转换成这样的嵌套 HTML 列表:

<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>

任何想法如何使用 Tempo 来完成?

4

2 回答 2

0

Tempo 1.x 无法处理多层嵌套模板。但是,2.0-dev 分支支持这一点,在我看来可以正确呈现您的数据:http: //jsfiddle.net/mr_olafsson/wLEQs/

请注意,该示例确实暗示了固定(且相等)数量的级别/嵌套模板。让我知道你是怎么办的!这么晚才回复很抱歉。

于 2012-08-31T11:03:23.487 回答
-1

我不知道节奏,我用 underscore.js 代替。

它会是这样的:

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

var htmlResult = _.template(mytemplate, myJSON);
于 2012-01-23T18:29:23.090 回答