高效且可重用 PHP 导航栏
Efficient and Reusable PHP Nav Bar
我正在尝试制作一个简单的PHP模板文件,我想知道如何制作一个高效的导航栏。
这是我目前拥有的:
<nav>
<ul>
<!-- If the pageName is equal to the specific page number, make it the active class in styles.css (linked to CSS in head.php) -->
<li <?php
if ($pageName === $pageName1)
{
echo "class = 'active'";
}
?>>
<!-- The link to the page (file will be named as the value of pageName1.php) -->
<!-- Then display the pageName with the first letter of each word capitalized -->
<?php echo "<a href=" . '"' . $pageName1 . ".php" . '"' . ">" . ucfirst($pageName) . "</a>"; ?>
</li>
</ul>
</nav>
它有效,但我想知道我是否可以提高它的效率并遵循更好的 PHP 做法。
您可以通过在顶部执行逻辑然后仅在 HTML 代码中输出变量来稍微简化它。
此外,您应该始终将 HTML 保留为 HTML,并避免使用 PHP 输出 HTML。
<?php
$active = ($pageName === $pageName1 ? ' class="active"' : '');
?>
<nav>
<ul>
<li<?= $active ?>>
<a href="<?= $pageName1 ?>.php"><?= ucfirst($pageName) ?></a>
</li>
</ul>
</nav>
我正在尝试制作一个简单的PHP模板文件,我想知道如何制作一个高效的导航栏。
这是我目前拥有的:
<nav>
<ul>
<!-- If the pageName is equal to the specific page number, make it the active class in styles.css (linked to CSS in head.php) -->
<li <?php
if ($pageName === $pageName1)
{
echo "class = 'active'";
}
?>>
<!-- The link to the page (file will be named as the value of pageName1.php) -->
<!-- Then display the pageName with the first letter of each word capitalized -->
<?php echo "<a href=" . '"' . $pageName1 . ".php" . '"' . ">" . ucfirst($pageName) . "</a>"; ?>
</li>
</ul>
</nav>
它有效,但我想知道我是否可以提高它的效率并遵循更好的 PHP 做法。
您可以通过在顶部执行逻辑然后仅在 HTML 代码中输出变量来稍微简化它。
此外,您应该始终将 HTML 保留为 HTML,并避免使用 PHP 输出 HTML。
<?php
$active = ($pageName === $pageName1 ? ' class="active"' : '');
?>
<nav>
<ul>
<li<?= $active ?>>
<a href="<?= $pageName1 ?>.php"><?= ucfirst($pageName) ?></a>
</li>
</ul>
</nav>