dotcraq3249 2012-03-06 21:27
浏览 103

如何使用php显示导航项显示正确的活动类

I am building a CMS and I have problems with my navigation. I want to add the class active to the active item in the navigation. This would work fine if I had a page for every item, but I have other sections and links

Here is my code:

<div id="main-menu">
<?php foreach ($items as $item) : ?>
    <?php $active = ''; ?>
    <?php if (isset($page)) : ?>
    <?php ($item->pageId === $page->id) ? $active = 'active' : $active = ''; ?>
    <?php endif; ?>
    <?php if ($item->link == '') : ?>
    <a href="<?php echo ROOT_PATH; ?>front/site/page?x=<?php echo $item->id; ?>" class="<?php echo $active; ?>"><?php echo $item->label; ?></a>
    <?php else : ?>
    <a href="<?php echo $item->link; ?>" class="<?php echo $active; ?>"><?php echo $item->label; ?></a>
    <?php endif; ?>
    <?php endforeach; ?>

When I do not have a page, then I give the link the value provided to point to the specific section. How can I make them all to work fine?

  • 写回答

2条回答 默认 最新

  • dongxingchang9345 2012-03-06 21:39
    关注

    You don't need that many <?php ?> tags! Anyway, your problem seem to be an incorrect usage of the ternary operator. Try this:

    <?php 
    foreach ($items as $item) :
        $active = ''; 
        if (isset($page)) :
            $active = ($item->pageId === $page->id) ? 'active' : '';
        endif;
        if ($item->link == '') :
            ?>
            <a href="<?php echo ROOT_PATH; ?>front/site/page?x=<?php echo $item->id; ?>" class="<?php echo $active; ?>"><?php echo $item->label; ?></a>
        <?php else : ?>
            <a href="<?php echo $item->link; ?>" class="<?php echo $active; ?>"><?php echo $item->label; ?></a>
        <?php
        endif;
    endforeach; 
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测