سؤال

I have a rather complicated question :)

I want to send data in form of json from the server to the client.

There the data shall be used by javascript to generate XHTML from this data.

Now I am looking for a library/framework that helps me generate this XHTML from JSON.

For example a solution could be to have special XHTML "template" files that contain variables which are mapped by name to a javascript method and that method takes the JSON array and fills some parts of the XHTML with the variables in the JSON array.

Example Template File (Pseudocode):

filename: TemplateA.something

<html>
Hello my name is %VARIABLE1% !
</html>

And the frameworks generates me then a method like that (Pseudocode):

generateXHTMLfromTemplate(templatename, data);

and it would return XHTML.

For example i would then call it like that (Pseudocode):

container.html(generateXHTMLfromTemplate('TemplateA', '{"VARIABLE1" : "Earl"}'));

Something like that would be great, the best would be code-completion of these "template" files in eclipse ;)

هل كانت مفيدة؟

المحلول 2

Taken from the comment of the post:

Something like this? github.com/janl/mustache.js – Blender yesterday

 

Others to choose from: doT, Handlebars, Underscore. – Pointy yesterday

نصائح أخرى

Despite I will probably be downvoted to oblivion, I will put a very simple alternative.

If you need a very simple functionality then you can use a very simple plugin as $.fn.loadtemplate, which is a modification of a previous one of mine $.fn.simpletemplate.

$.fn.loadtemplate = function(resource, variables) {
    return this.each(function() {
        var $self = $(this);
        $.ajax({
            url: resource,
            dataType: "html",
            success: function(html) {
                html = html.replace(/{{(.+)}}/g, function(match, variable) {
                    return variables[variable];
                });
                $self.html(html);
            }
        });
    });
};

All the {{variable}} tokens will be replace by its appropriate properties of the given object passed to the function.

<!-- template.tpl -->
<h1>Hello my name is {{name}}!</h1>

$("#selector").loadtemplate("template.tpl", {
  name: "World"
});​

An example fiddle here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top