【问题标题】:Is it possible to automatically render the header and footer on all pages?是否可以在所有页面上自动呈现页眉和页脚?
【发布时间】:2021-05-22 04:03:32
【问题描述】:

免责声明:我完全是编程新手。我有通过反复试验编辑代码的经验,但我没有任何真正的知识。

我希望从头开始建立一个网站。如何做到这一点,以便我不必将相同的页眉/页脚代码粘贴到每个页面?我假设页眉/页脚有一个指定的文件;在我想要包含页眉/页脚的页面上,我必须包含一行代码才能调用它?

还发现了类似的问题/主题/线程:Use same header and footer on all webpages

【问题讨论】:

  • 不是默认的,没有。这完全取决于您使用的服务器。如果您使用的是 Node,那么 Uttam 的答案可能是可靠的。如果您使用的是 PHP,则可以使用简单的 PHP 命令插入页眉/页脚。如果您使用 Ruby,ERB 模板语言可以做与 PHP 相同的事情。

标签: html


【解决方案1】:

如果您希望这样做只使用 Html 是不可能的,但您可以在 html 中使用 JavaScript 创建一个自定义属性,该属性将包含您的 html 文件。你可以在这里阅读更多相关信息 - template tag examples

这不是最好的解决方案,我个人不会建议您这样做,因为您是初学者。 起初这可能会让人不知所措,但您现在不需要理解或学习它。举个简单的例子-

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test File</title>
</head>
<body>

    <div include-your-html = "header.html">
    <!--Cosidering I have header.html file in the same directory-->
    <p>This is my body</p>
    <div include-your-html = "footer.html">
    <!--Cosidering I have footer.html file in the same directory-->
    
    <!--You can use this script to set the attribute-->
    <script>
    function includeHTML() {
        var z, i, elmnt, file, xhttp;
        z = document.getElementsByTagName("*");
        for (i = 0; i < z.length; i++) {
            elmnt = z[i];
            file = elmnt.getAttribute("include-your-html");
            if (file) {
                xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4) {
                        if (this.status == 200) {elmnt.innerHTML = this.responseText;}
                        if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
                        elmnt.removeAttribute("include-your-html");
                        includeHTML();
                    }
                }
                xhttp.open("GET", file, true);
                xhttp.send();
                return;
           }
       }
    }
    includeHTML()
    </script>
</body>
</html>

对于某些人来说,这可能由于 CORS 政策而被阻止,您可以设置一个 CORS 代理来解决这个问题。更多详细信息请访问sideshowbarker's answer here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2019-10-01
    • 2014-07-24
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多