使用 JavaScript 加载 HTML 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6451169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:46:58  来源:igfitidea点击:

Load HTML template with JavaScript

javascripthtmltemplates

提问by iancrowther

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?

我有“templates.html”,其中包含我想加载到 JavaScript 中并使用的 HTML 片段的集合。记住templates.html 不是加载的DOM 文档,访问模板/片段的好方法是什么?

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

我正在考虑使用document.open创建一个 DOM 来访问,但我认为这在某些浏览器上有问题。

采纳答案by kleinohad

You can load the html into a hidden div and then you will have a DOM access the easiest way to load the html to a DIV is using jquery load: http://api.jquery.com/load/

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

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

回答by peterp

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

使用 jQuery 和.load()( http://api.jquery.com/load/) 方法将加载的文档注入 DOM。

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

回答by olanod

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

这有点旧,但由于“使用 JavaScript 加载 HTML 模板”现在应该指的是加载HTMLTemplateElement这里是一种更现代的方法,用于使用 javascript 加载本机模板,也适用于您的用例。

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.

首先,使用<template>已经比将 HTML 加载到隐藏的 DIV 中要好,因为模板是内部的并且不显示内容。您可以从一开始就渲染模板,并在需要时使用它们。

<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.

因为我们希望根据从网络中获取的一些文本来构建模板的内容,所以我们必须对其进行解析并将其添加到我们的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.htmlalready 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.

如果my-template.html已经包含在<template>标签中,我们可以避免手动创建模板元素的部分,因为 DOMParser 已经为我们创建了模板元素。

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

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

是我一直用来将模板动态加载到文档中的片段,它使用了我刚刚解释的内容。

回答by Andrei-Niculae Petre

another way to do this is using requireJS.

另一种方法是使用requireJS

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

回答by IvanM

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();  

回答by Nerdroid

you could load the template async using jquery ajax

您可以使用 jquery ajax 加载模板异步

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