Search code examples
prototypejshandlebars.js

How to create element from HTML in Prototype?


Is there a way to create element from HTML in Prototype that's an analog to jQuery's $('<div>Foo</div>')?

Basically I create HTML chunk from a Handlebars template and want to insert into DOM but don't want to wrap it in some other element.


Solution

  • I added this function as a 'static method' to Mustache for one of my recent projects to solve the same problem. I don't believe there is anything built-in to Prototype to solve this. I used hidden textareas to hold my template code, hence the $F() call. The last 3 lines are more specific to your problem - create a new div, insert your applied template html, then return the first descendant (as an element, by this point). This assumes your template only ever has one root element.

    Mustache.createElementFromTemplateId = function(templateId, data) {
        if (!this.cachedTemplates) this.cachedTemplates = {};
    
        var templateStr = this.cachedTemplates[templateId];
        if (!templateStr) {
            templateStr = $F(templateId);
            this.cachedTemplates[templateId] = templateStr;
        }
    
        var appliedTemplateStr = this.render(templateStr, data);
    
        var div = new Element("div");
        div.insert( appliedTemplateStr );
        return div.firstDescendant();
    };