简体   繁体   English

高效且可重复使用的PHP导航栏

[英]Efficient and Reusable PHP Nav Bar

I am trying to make a simple PHP template files, and I was wondering how to make an efficient navigation bar. 我试图制作一个简单的PHP模板文件,并且想知道如何制作一个高效的导航栏。

This is currently what I have: 这是我目前拥有的:

<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>

It works, but I am wondering if I can make it more efficient and follow better PHP practices. 它可以工作,但是我想知道是否可以提高它的效率并遵循更好的PHP实践。

You can simplify it somewhat by doing the logic at the top and then only outputting variables inside the HTML code. 您可以通过在顶部执行逻辑,然后仅在HTML代码内部输出变量来对它进行某种程度的简化。

Also, you should always leave HTML as HTML, and avoid using PHP to output the 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM