简体   繁体   中英

Load HTML template with JavaScript

I am struggling to find a clean solution to my problem and was wondering if anyone could offer some tips.

I have "templates.html" which contains a collection of HTML snippets which I want to load into JavaScript and use. What is a good way to access the templates/snippets bearing in mind that templates.html is not a loaded DOM document?

I was thinking about using document.open to create a DOM to access but I think this has issues on certain browsers.

Use jQuery and the .load() ( http://api.jquery.com/load/ ) method to inject the loaded document into the DOM.

$(function() {
    $('#content').load('/templates.html');
});

你可以将html加载到一个隐藏的div中然后你将有一个DOM访问权限,最简单的方法是将html加载到DIV使用jquery load: http//api.jquery.com/load/

$( "#result" ).load( "ajax/test.html" );

This is a bit old but since "Load HTML template with JavaScript" nowadays should refer to the loading of a HTMLTemplateElement here is a more modern looking approach to loading natives templates with javascript that also works for your use case.

First of all using <template> is already better than loading HTML into a hidden DIV because templates are innert and don't display content. You can have the templates being rendered from the beginning and use them whenever you need.

<html>
<head>
  <template>My template</template>
</head>
<body>
  <script>
  document.body.append(
    document.importNode(
      document.querySelector('template').content,
      true
    )
  )
  </script>
</body>
</html>

Or create them dynamically.

const template = document.createElement('template')
// modify the template's content
template.content.append(document.createElement('div'))
// add it to the document so it is parsed and ready to be used
document.head.append(template)

Because we want the content of the template to be built based on some text we get from the network, we have to parse it and add it to our template.content .

const text = fetchTemplateSomehowAsText('my-template.html')
const parsedDocument = new DOMParser().parseFromString(text, 'text/html')
template.content.append(parsedDocument.querySelector('#my-snippet'))

If my-template.html already comes wrapped in the <template> tag we can avoid the part of creating the template element manually because the DOMParser already creates the template element for us.

document.head.append(
  new DOMParser().parseFromString(text, 'text/html')
    .querySelector('template')
  )
)

This is a snippet I've been using to load templates into the document dynamically that uses what I just explained.

another way to do this is using requireJS .

require (['text!template_name'], function(yourTemplate) {
  // do stuff in here with yourTemplate dinamically load
}

For simple requiring you can try:

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {     
        //do something with xhr.responseText
    }   
};      
xhr.open('GET', '/template.html');
xhr.send();  

you could load the template async using jquery ajax

$.get("/html/template01.html")
.done((data) => {
    console.info(data); // output the content of the html file
});

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