使用 php 在菜单项上设置活动类

2022-01-06 00:00:00 php html menu

我有一个由

  • 元素和一个 class="active" 元素组成的简单菜单,用于标记当前页面.$_get[] 传递一个变量,通过 url 选择特定页面:?pg=PAGE.

    I have a simple menu made of <ul><li> elements and a class="active" in place to mark the current page. A variable is passed by $_get[] to select the specific page by url: ?pg=PAGE.

    我对 php 还很陌生,还在学习中.这工作得很好,但我觉得应该有一种更简单、更短的方法.

    I am fairly new to php and still learning. This works just fine, but i feel there ought to be a simpler and shorter way.

    <ul class="nav">
      <li <?php if ($_GET['pg'] == "PAGE1") { echo "class="active""; } ?>><a href="?pg=PAGE1">FIRST PAGE</a></li>
      <li <?php if ($_GET['pg'] == "PAGE2") { echo "class="active""; } ?>><a href="?pg=PAGE2">SECOND PAGE</a></li>
    </ul>
    

    推荐答案

    <?php
        $pages = array(
            'PAGE1' => 'FIRST PAGE',
            'PAGE2' => 'SECOND PAGE');
    ?>
    
    <ul class="nav">
      <?php foreach ($pages as $pageId => $pageTitle): ?>
      <li <?=(($_GET['pg'] == $pageId) ? 'class="active"' : '')?>><a href="?pg=<?=$pageId?>"><?=$pageTitle?></a></li>
      <?php endforeach; ?>
    </ul>
    

    http://php.net/manual/en/control-structures.foreach.php

    不要重复自己——两个 li-s 非常相似,唯一的区别是页面 ID 和标题.一旦您拥有两个以上的页面,这种方法将非常有用.

    Don't repeat yourself -- both li-s are very similar, the only difference is in page ID and title. This approach will really help once you have more than two pages.

    尽量将 PHP 和 HTML 分开——一旦您决定将它们保存在单独的文件中(有时您会这样做),这将使您的生活更轻松.

    Try to keep PHP and HTML as separate as possible -- this will make your life easier once you decide to keep them in separate files (and you will sometimes).

相关文章