简体   繁体   中英

How to get Handlebars templates to return DOM elements instead of string of HTML?

I am using Handlebars in my Backbone.js application. I am wondering how to get Handlebars template to return DOM elements instead of a string?

This is what I mean:

define([
    'underscore',
    'backbone',
    'handlebars',
    'text!templates/myTemplate.hbs'
], function(_, Backbone, handlebars, template) {
   ...
   ...
   render: function() {
       // This returns me a string of HTML, I would like to be able
       // to get actual DOM elements so that I can use appendChild
       // and insertBefore etc.
       var hbTemplate = Handlebars.compile(template);
       var templateString = hbTemplate(/* some json data */);
   },
   ...
   ...

I have tried to use DOMParser to parse the HTML string into DOM elements but there are syntax errors due to a lot of extra spaces from the Handlebars template. But it would be nice if Handlebars can somehow return the DOM elements instead of me parsing them myself.

you can pipe the output to jQuery(if that is a option) that parses handlebar templates to my knowledge. dont know if jQuery is a option but somthing like:

var hbTemplate = Handlebars.compile(template);
var templateJqueryDom = $(hbTemplate(/* some json data */))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM