博客 / 建站

网站建设中 HTML模板的复用方法有哪些

要在不同页面复用 HTML 的 <head><footer> 部分,你可以将这两个部分提取到单独的 PHP 文件中,并在需要的页面中引入它们。以下是两种常用的方法来实现:

在 WordPress 中,get_header()get_footer() 函数是非常常用的方式,可以将 <head><footer> 部分分离到模板文件中。

步骤:

  1. 创建 header.php 文件:

在你的主题根目录中,创建一个 header.php 文件,并将 <head> 部分的内容放入其中。

<!-- header.php -->
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php wp_title(); ?></title>
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
  1. 创建 footer.php 文件:

在你的主题根目录中,创建一个 footer.php 文件,并将 <footer> 部分的内容放入其中。

<!-- footer.php -->
<footer>
    <p>&copy; <?php echo date('Y'); ?> Your Company Name. All rights reserved.</p>
</footer>
<?php wp_footer(); ?>
</body>
</html>
  1. 在页面模板中引入头部和脚本:

在你需要复用的页面模板中,通过 get_header()get_footer() 来引入这些部分。

<?php get_header(); ?>

<!-- 页面内容 -->

<?php get_footer(); ?>

二. 使用 includerequire(适用于任何 PHP 项目)

如果你不使用 WordPress,你可以在普通 PHP 项目中使用 includerequire 来引入头部和脚本。

1、创建 header.php 文件:

<!-- header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网站标题</title>
    <!-- 其他头部内容 -->
</head>
<body>

2、创建 footer.php 文件:

<!-- footer.php -->
<footer>
    <p>&copy; <?php echo date('Y'); ?> Your Company. All rights reserved.</p>
</footer>
</body>
</html>

3、在页面中使用 include 引入:

<?php include('header.php'); ?>

<!-- 页面内容 -->

<?php include('footer.php'); ?>

三、使用模板引擎(如 Twig)

如果你在项目中使用了像 Twig 这样的模板引擎,你可以将头部和脚部内容抽象到模板中,然后在其他模板中复用它们。例如:

<!-- base.html.twig -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    {% block content %}{% endblock %}

    <footer>
        <p>&copy; {{ "now"|date("Y") }} Your Company. All rights reserved.</p>
    </footer>
</body>
</html>

<!-- page.html.twig -->
{% extends "base.html.twig" %}

{% block content %}
    <h1>这是页面的内容</h1>
{% endblock %}

总结

  • WordPress: 使用 get_header()get_footer() 来复用 <head><footer> 部分。
  • PHP: 使用 includerequire 引入头部和脚部。
  • 模板引擎: 如果使用像 Twig 这样的模板引擎,可以通过继承父模板来复用头部和脚部部分。

你可以根据你的项目需求选择适合的方案。

评论留言

您的邮箱地址不会被公开。 必填项已用 * 标注