【问题标题】:HTML: Is it possible to import html files as templates (like calling a function)?HTML:是否可以将 html 文件作为模板导入(如调用函数)?
【发布时间】:2020-09-03 08:59:53
【问题描述】:

(先在这里询问,提前感谢您的帮助!)

有没有办法从另一个文件中导入 html 来充当模板?类似于调用函数。

主要原因是为了简化对整个网站所做的任何更改;例如更改标题导航菜单会影响整个网站的设计。

【问题讨论】:

  • 类似于 Elementor 上的“全局”功能

标签: html templates


【解决方案1】:

HTML 没有内置的功能可以做到这一点。最接近的是 <iframe> 元素,它们将单独的文档加载到嵌入式视口中。

这个问题通常最好通过在 HTML 到达浏览器之前组合你重用的组件来解决。

这可以使用某种形式的服务器端编程(例如 SSI、PHP 包含或模板语言)或在构建时(通常使用 static site generator)来完成。

【讨论】:

    【解决方案2】:

    您可以开始使用Custom Elements,但是Opera 和Safari 缺乏支持。刚开始看感觉很吃力,需要有javascript的经验,但是上手之后就很流畅了。

    您还可以使用 Vue、React、Angular 和 Polymer 等框架,让自定义元素更进一步。

    【讨论】:

      【解决方案3】:

      我认为最接近的是将 html 代码用<template> 标签包围,然后执行 Javascript 代码,根据该模板生成最终的 HTML 文档。类似的东西:

      <!DOCTYPE html>
      <html>
      <body>
      <style>
      .myClass {
        color: white;
        background-color: DodgerBlue;
        padding: 5px;
        text-align: center;
        margin: 10px;
      }
      </style>
      
      <h2>The template demo</h2>
      
      
      <button onclick="showContent()">Generate document</button>
      
      <template>
        <div class="myClass">I like: </div>
      </template>
      
      <script>
      var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
      
      function showContent() {
        var temp, item, a, i;
        temp = document.getElementsByTagName("template")[0];
        item = temp.content.querySelector("div");
        for (i = 0; i < myArr.length; i++) {
          a = document.importNode(item, true);
          a.textContent += myArr[i];
          document.body.appendChild(a);
        }
      }
      </script>
      
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-07
        • 2017-04-28
        • 1970-01-01
        • 1970-01-01
        • 2017-08-09
        • 1970-01-01
        • 2012-02-13
        • 2018-11-23
        相关资源
        最近更新 更多