简体   繁体   中英

How to add dynamically a “x-tmpl” script from a scripts page to HTML page?

I have tried to use different methods :

  • add in body innerHtml script part
  • create script element with type "x-tmpl"

But that did not work. Can you help me, please ?

Thank you.

I encountered a similar issue when trying to dynamically load Handlebars templates, so instead of trying to insert <script> elements into the DOM, I simply stored compiled templates into a global Javascript object:

var TEMPLATES = {};    

/**
 * Gets Handlebars template, either from JS if already loaded, or via AJAX request
 * @param name Name of template
 * @param data JSON data for use in template
 * @returns Handlebars template
 */
function get_template(name,data) {
  if(typeof TEMPLATES[name] != 'undefined') {
    return TEMPLATES[name];
  } else {
    $.get(
      TEMPLATE_ROOT + name + '.hb',
      function(template) {
        TEMPLATES[name] = Handlebars.compile(template);
        render_template(name,data);
      }
    );
    return null;
  }
}

Notice my call to render_template(name,data) following the successful loading of the template. That simply calls my function to again attempt to render the template, which will now be in memory:

/**
 * Render JSON using Handlebars template
 * @param name Name of Handlebars template
 * @param data JSON data to render
 */
function render_template(name,data){
  var template = get_template(name,data);
  if(template !== null) {
    $('#main').html(template(data.transforms[1].data));
  }
}

I am making a lot of assumptions about what you're trying to do, so hopefully this will be helpful.

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