【问题标题】:Transforming tree structure using Tempo使用 Tempo 转换树结构
【发布时间】:2012-02-16 23:16:40
【问题描述】:

我已经开始在一个小型 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 来完成?

【问题讨论】:

    标签: javascript html json recursion tempo


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我不知道节奏,我用 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 2022-01-01
        • 2018-09-04
        • 1970-01-01
        • 2017-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多