使用流程控制替换语法
将演示网站的首页和产品页进行动态替换
- 创建一个data文件夹
文件夹里面创建header.php和items.php - 在对应的相关文件位置进行替换,代码如下:
header.php
<?php
return [
[
'id' => 1,
'url' => 'index.php',
'title' => '首页',
],
[
'id' => 2,
'url' => 'news.php',
'title' => '新闻',
],
[
'id' => 3,
'url' => 'items.php',
'title' => '产品',
],
[
'id' => 4,
'url' => 'contact.php',
'title' => '联系',
],
[
'id' => 5,
'url' => 'login.php',
'title' => '登陆',
]
]
?>
items.php
<?php
// 索引数组语义化:关联数组
return [
[
'id' => 1,
'title' => '微信小程序1',
'img' => 'static/images/item1.jpeg',
],
[
'id' => 2,
'title' => '网站设计2',
'img' => 'static/images/item2.jpeg',
],
[
'id' => 3,
'title' => '微信小程序3',
'img' => 'static/images/item3.jpeg',
],
[
'id' => 4,
'title' => '微信小程序4',
'img' => 'static/images/item4.jpeg',
],
[
'id' => 5,
'title' => '微信小程序5',
'img' => 'static/images/item5.jpeg',
],
[
'id' => 6,
'title' => '微信小程序6',
'img' => 'static/images/item6.jpeg',
],
[
'id' => 7,
'title' => '微信小程序7',
'img' => 'static/images/item7.jpeg',
],
[
'id' => 8,
'title' => '微信小程序8',
'img' => 'static/images/item8.jpeg',
],
];
插入文件相应位置 index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>首页</title>
<link rel="stylesheet" href="static/css/style.css" />
</head>
<body>
<header>
<nav>
<?php
$news = include './data/header.php';
?>
<?php foreach ($news as $new) : ?>
<a href="<?= $new['url'] ?>"><?= $new['title'] ?></a>
<?php endforeach ?>
</nav>
</header>
<!-- 主体 -->
<main>
<!-- 产品列表 -->
<?php
$items = include './data/items.php';
?>
<div class="items">
<h3>产品列表</h3>
<div class="list">
<?php foreach ($items as $item) : extract($item) ?>
<div class="item">
<img src="<?= $img ?>" alt="" />
<a href=""><?= $title ?></a>
</div>
<?php endforeach ?>
</div>
</div>
<!-- 分页条 -->
<p class="pagebar">
<a href="">1</a>
<a href="">...</a>
<a href="">6</a>
<a href="">7</a>
<a href="" class="active">8</a>
<a href="">9</a>
<a href="">10</a>
<a href="">...</a>
<a href="">20</a>
</p>
</main>
<?php
include './data/footer.php'
?>
</body>
</html>