Class active when on page using php

你。 提交于 2019-12-23 04:29:25

问题


I have an include file that includes the header and footer of my site. But in the header I use an active class to let the menu-item change when on that page. How can you achieve this using one include file? With PHP?

I found this:

index.php

<?php $page == 'one'; include('includes/header.php'); ?>

header.php

<li>
      <a <?php echo ($page == 'one') ? "class='active'" : ""; ?> 
             href="contact.php">Contact</a>/</li>

But it's not changing, when I just used the class on every page seperately, it worked.


回答1:


Index.php

<?php $page = 'one'; include('includes/header.php'); ?>

$page = 'one'. "==" is a comparison operator http://www.php.net/manual/en/language.operators.comparison.php

Header.php

<li><a href="#"<?php if($page == 'one'){ echo ' class="active"';}?>>LINK</a></li>

I think is more clean like that




回答2:


just move the echo to correct place(s), because your syntax is not correct

Like this;

<li>
  <a 
    <?php
      echo( $page == 'one'  ? "class='active'" : ""); 
     ?> 
   href="contact.php">Contact</a>
/
</li>

And also you should correct this in include.php

$page = 'one';

with single "=" sign




回答3:


<?php 
     $page = 'one'; 
     include('includes/header.php'); 
 ?>

$page =1; not $page == 1; because it is assignment of a variable.

Rest of the code is fine.



来源:https://stackoverflow.com/questions/21254404/class-active-when-on-page-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!