如何使用 php 将 class='active' 添加到 html 菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2913415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How add class='active' to html menu with php
提问by patad
I want to put my html navigation in a separate php file so when I need to edit it, I only have to edit it once. The problem starts when I want to add the class active to the active page.
我想把我的 html 导航放在一个单独的 php 文件中,所以当我需要编辑它时,我只需要编辑一次。当我想将活动类添加到活动页面时,问题就开始了。
I've got three pages and one common file.
我有三页和一个公共文件。
common.php :
常见的.php :
<?php
$nav = <<<EOD
<div id="nav">
<ul>
<li><a <? if($page == 'one'): ?> class="active"<? endif ?> href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
index.php :All three pages are identical except their $page is different on each page.
index.php :除了每个页面的 $page 不同之外,所有三个页面都是相同的。
<?php
$page = 'one';
require_once('common.php');
?>
<html>
<head></head>
<body>
<?php echo $nav; ?>
</body>
</html>
This simply won't work unless I put my nav on each page, but then the whole purpose of separating the nav from all pages is ruined.
除非我将导航放在每个页面上,否则这根本行不通,但是将导航与所有页面分开的整个目的就被破坏了。
Is what I want to accomplish even possible? What am I doing wrong?
我想要完成的事情甚至可能吗?我究竟做错了什么?
Thanks
谢谢
EDIT: When doing this, the php code inside the li don't seem to run, it's just being printed as if it was html
编辑:执行此操作时,li 中的 php 代码似乎没有运行,它只是像 html 一样被打印出来
采纳答案by Joseph
Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.
您的 index.php 代码是正确的。我在下面包含了 common.php 的更新代码,然后我将解释差异。
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
The first issue is that you need to make sure that the end declaration for your heredoc -- EOD;-- is not indented at all. If it is indented, then you will get errors.
第一个问题是您需要确保您的heredoc 的结束声明 -- EOD;-- 根本没有缩进。如果它是缩进的,那么你会得到错误。
As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)
至于你的 PHP 代码没有在 heredoc 语句中运行的问题,那是因为你看错了。使用 heredoc 语句与关闭 PHP 标签不同。因此,您无需尝试重新打开它们。那对你无济于事。Heredoc 语法的工作方式是,开头和结尾之间的所有内容都完全按照所写的方式显示,变量除外。这些被替换为关联的值。我从 heredoc 中删除了你的逻辑,并使用了一个三级函数来确定类,以便更容易看到(尽管我不相信任何逻辑语句都可以在 heredoc 中工作)
To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:
要理解heredoc 语法,它与将它包含在双引号(") 中是一样的,但不需要转义。因此您的代码也可以这样编写:
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:
它会做完全相同的事情,只是写得有些不同。Heredoc 和字符串之间的另一个区别是,您可以从中间的字符串中逃脱,而在heredoc 中则不能。使用此逻辑,您可以生成以下代码:
<?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
Then you can include the logic directly in the string like you originally intended.
然后,您可以按照最初的意图将逻辑直接包含在字符串中。
Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.
无论您选择哪种方法,对脚本性能的影响都非常小(如果有的话)。它主要归结为偏好。无论哪种方式,您都需要确保了解每种方式的工作原理。
回答by Mihai Toader
why don't you do it like this:
你为什么不这样做:
in the pages:
在页面中:
<html>
<head></head>
<body>
<?php $page = 'one'; include('navigation.php'); ?>
</body>
</html>
in the navigation.php
在导航.php
<div id="nav">
<ul>
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="index1.php">Tab1</a>/</li>
<li>
<a <?php echo ($page == 'two') ? "class='active'" : ""; ?>
href="index2.php">Tab2</a>/</li>
<li>
<a <?php echo ($page == 'three') ? "class='active'" : ""; ?>
href="index3.php">Tab3</a>/</li>
</ul>
</div>
You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.
实际上,您将能够控制在页面中放置导航的位置以及传递给它的参数。
Later edit: fixed syntax error.
后来编辑:修复了语法错误。
回答by Lance
A very easy solution to this problem is to do this.
解决这个问题的一个非常简单的方法就是这样做。
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>
Which will output
哪个会输出
<ul>
<li class="current"><a href="index.php">Home</a></li>
<li class=""><a href="portfolio.php">Portfolio</a></li>
<li class=""><a href="services.php">Services</a></li>
<li class=""><a href="contact.php">Contact</a></li>
<li class=""><a href="links.php">Links</a></li>
</ul>
回答by CharlesLeaf
I think you need to put your $page = 'one';above the require_once.. otherwise I don't understand the question.
我认为你需要把你$page = 'one';的 require_once放在上面。否则我不明白这个问题。
回答by Ondrej Slinták
Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:
为什么不为此导航创建一个函数或类并将活动页面作为参数放在那里?这样你就可以称之为,例如:
$navigation = new Navigation( 1 );
or
或者
$navigation = navigation( 1 );
回答by Don Gilbert
I know this is old, but none of these answers are very good (sry ppl)
我知道这是旧的,但这些答案都不是很好(sry ppl)
The BEST way to do it (without writing out convoluted classes) is to compare the current $_SERVER['REQUEST_URI'] to the href of the link. You're almost there.
最好的方法(不写出复杂的类)是将当前的 $_SERVER['REQUEST_URI'] 与链接的 href 进行比较。您快到了。
Try this. (Taken from http://ma.tt/scripts/intellimenu/)
尝试这个。(取自http://ma.tt/scripts/intellimenu/)
$nav = <<<EOD
<div id="nav">
<ul>
<li><a href="index.php">Tab1</a></li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
$lines = explode("\n", $nav);
foreach($lines as $line)
{
if(preg_match('/href="([^"]+)"/', $line, $url)) {
if(substr($_SERVER['REQUEST_URI'], 0, 5) == substr($url[1], 0, 5)) {
$line = str_replace('><a', ' class="current-menu-item"><a', $line);
}
}
echo $line . "\n";
}
回答by Murkle
You could use this PHP, hope it helps.
你可以使用这个 PHP,希望它有帮助。
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
因此,列表将如下所示。
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>
回答by geocar
$page='one'should occur beforeyourequire_once()not after. After is too late- the code has already been required, and$navhas already been defined.You should use
include('header.php');andinclude('footer.php');instead of setting a$navvariable early on. That increases flexibility.Make more functions. Something like this really makes things easier to follow:
function maybe($x,$y){return $x?$y:'';} function aclass($k){return " class=\"$k\" "; }then you can write your "condition" like this:
<a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....
$page='one'应该发生在你之前require_once()而不是之后。之后为时已晚 - 代码已经被需要,并且$nav已经被定义。您应该使用
include('header.php');andinclude('footer.php');而不是$nav尽早设置变量。这增加了灵活性。做更多的功能。像这样的事情确实让事情更容易遵循:
function maybe($x,$y){return $x?$y:'';} function aclass($k){return " class=\"$k\" "; }那么你可以这样写你的“条件”:
<a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....
回答by Pankaj Upadhyay
CALL common.php
<style>
.ddsmoothmenu ul li{float: left; padding: 0 20px;}
.ddsmoothmenu ul li a{display: block;
padding: 40px 15px 20px 15px;
color: #4b4b4b;
font-size: 13px;
font-family: 'Open Sans', Arial, sans-serif;
text-align: right;
text-transform: uppercase;
margin-left: 1px; color: #fff; background: #000;}
.current .test{ background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php" class="test">Home <i>::</i> <span>welcome</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>"><a href="about.php" class="test">About us <i>::</i> <span>Who we are</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>"><a href="course.php">Our Courses <i>::</i> <span>What we do</span></a></li>
</ul><!-- end #dropdown-menu -->
</div><!-- end .span8 -->
add each page
<?php include('common.php'); ?>
回答by Vijaya Subramaniyan
<ul>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>
</ul>

