是否有一个包装HTML的Javascript模板系统?

时间:2010-08-29 04:18:06

标签: html ruby xml json templates

我想知道是否有类似Javascript模板系统包装HTML的东西,所以我们不必直接处理HTML(是的,我知道这是一个坏主意,但只是出于好奇)。

所以不要写HTML:

<body>
  <div id="title">Great work!</div>
  <span>My name is Peter</span>
</body>

我们在Json写道:

body: [
  {div: [
    {id: "title"},
    {body: "Great work!"}
  ]
  {span: [
    {body: "My name is Peter"}
  ]
]

我知道它看起来有点奇怪,但我真的很喜欢一切都是对象的东西:)

对于任何语言都有这样的实现吗? (我自己使用Ruby)。

编辑:找到一些有趣的东西:

http://jsonml.org/

看看他们的例子!辉煌!

2 个答案:

答案 0 :(得分:1)

我刚刚编写了一个解析器的小例子,类似于你提到的,使用普通的旧JavaScript。我的代码有点脏(正如Casey Hope所提到的,你不应该扩展Object.prototype,或许,但是它很有用,我希望。

功能本身:

Object.prototype.toHtml = function(options)
{
    //Iterates over elements
    var processElements = function(obj, handler)
    {
        //Stores found elements
        var elements = [];

        for (var elem in obj)
        {
            //Skips all 'derived' properties
            if (!obj.hasOwnProperty(elem)) continue;

            //Attribute
            if (elem.indexOf("_") == 0)
            {
                elements.push({type: "attribute", name : /^_([a-z][0-9a-z]+)$/i(elem)[1], value : obj[elem]});
            }
            //Internal contents
            else if (elem == "contents")
            {
                elements.push({type: "contents", value : obj[elem]});
            }
            //Text node
            else if (elem == "text")
            {
                elements.push({type: "text", value : obj[elem]});
            }
            //Ordinary element
            else
            {
                elements.push({type: "element", name : elem,  value : obj[elem]});
            }
        }

        //Returns parsed elements
        return elements;
    }

    //Internal function to deal with elements
    var toHtmlInternal = function(name, elements)
    {
        //Creates a new element by name using DOM
        var element = document.createElement(name);

        //Element children and attributes
        var children = processElements(elements);

        for (var i = 0; i < children.length; i++)
        {
            switch (children[i]["type"])
            {
                case "element":
                    element.appendChild(toHtmlInternal(children[i]["name"], children[i]["value"]));
                    break;
                case "attribute":
                    element.setAttribute(children[i]["name"], children[i]["value"]);
                    break;
                case "text":
                    element.appendChild(document.createTextNode(children[i]["value"]));
                    break;
                case "contents":
                    for (var j = 0; j < children[i]["value"].length; j++)
                    {
                        var content = children[i]["value"][j];
                        if (typeof content == "string")
                        {
                            element.appendChild(document.createTextNode(content));
                        }
                        else if (typeof content == "object")
                        {
                            element.appendChild(content.toHtml().firstChild);
                        }
                    }
                    break;
            }
        }

        //Returns it
        return element;
    }

    //Initial element checkment
    var initial = processElements(this);
    //Generic wrapper
    var wrapper = document.createElement("div");

    for (var i = 0; i < initial.length; i++)
    {
        if (initial[i]["type"] == "element")
        {
            wrapper.appendChild(toHtmlInternal(initial[i]["name"], initial[i]["value"]));
        }
    }

    //Returns wrapper
    return wrapper;
};

使用方法:

//A simple testing template
var html = ({
    //Element name is just a plain name here
    body: {

      //Nested element
      div : {
        //All attributes are prepended with underscore
        _id : "title",
        //Content of the element is represented by such construction
        text : "Great work!"
      },

      span : {
        text : "My name is Peter"
      },

      h1 : {
        _class : "common",
        //Elements can be defined using 'contents' notation also, so we could include text nodes
        contents : ["This is my ", {a : {text: "beautiful"}} , " header"]
      }

    }
}).toHtml();

alert(html.innerHTML); 

答案 1 :(得分:0)

您还应该查看haml。它非常酷!它不是JSON,但它的基本原理是一样的。您不必处理HTML。