I have a function called 'kmenu'
function kmenu()
{
if (isset($_GET['pid'])) {
$pid = $_GET['pid'];
} else {
$pid = 1;
}
$menu = '<ul class="nav navbar-nav">
<li class="active">HOME <span class="sr-only">(current)</span></li>
<li>ABOUT US</li>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-expanded="false">OUR PRODUCTS<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>Arabic Sweets</li>
<li>Cakes</li>
<li>Bakery</li>
<li>Chocolate</li>
<li>Confectionery</li>
<li>Ice Cream</li>
<li>Malaga</li>
</ul>
</li>
<li>OUR BRANCHES</li>
<li>GALLERY</li>
<li>CONTACT US</li>
</ul>';
return $menu;
}
this function content all the menu items as shown above.
I need to add the class='active' to the current page.
I used to make it like this before
if($pid==1){echo 'class="active"'} but when I try to use functions to store the menu how can I do this now.
OK. At first You can do something like this:
$menu = 'MENU';
$menu = $menu.'SOMETHINGELSE';
print_r($menu); // or return $menu;
In that case it will print / return "MENUSOMETHINGELSE". This is string concatenation. So You can do simple if (as You said you make it before), and write:
$menu = '';
$menu .= 'BEGINNING OF THE HTML';
if($pid==1) {
$menu .= 'class="active"';
}
$menu .= 'REST OF HTML';
Few more words:
But this is not everything. Storing menu in a variable looks really bad. Also outputing HTML like that too. You should try to save only important value in array, and then return / echo menu in loop. For example:
$menu = array(
[0] => array('name' => 'NAME0', 'title' => 'TITLE0', 'url' = '/url0'),
[1] => array('name' => 'NAME1', 'title' => 'TITLE1', 'url' = '/url1')
);
Then generate menu:
foreach ($menu as $m) {
echo ''.$m['name'].'';
}
In that case, visual settings are in foreach loop, and menu semantic in simple array. You can store active in that array too.
If You want, You can also take a look at ob_start functions, and use echo, and then return ob_get_contents(), if this is easier for You (http://php.net/manual/en/ref.outcontrol.php).
Remember that on every fragment of PHP code You can escape php.
<?php echo "ASD"; ?>
ASD
<?php echo "ASD"; ?>
This code will output three ASD. You should try to use this technique, and minimize echo ouput of Your application. You can also use it in loops:
<?php foreach ($menu as $m) { ?>
<a href="<?php echo $m['url']; ?>"
title="<?php echo $m['title']; ?>">
<?php echo $m['name']; ?>
</a>
<?php } ?>
I hope You get the idea. If there is much more constant html (as in Your example) this should be much more cleaner to output.
Another thing is storing the menu content inside a function. It is also not a good practice. You should try to switch to object programming style, and try to save this menu array in some sort of global / cache / another object.
In Your case, if someone needs to create two menus on the same site, each time he must call this function, and the whole menu variable is declared from the beginning. While it should be only accessible from the function.
If You dont need to make an object oriented application, or need an easier solution, it is much better to save $menu somewhere else (level higher), and pass it as an argument to for example menu_generator function.
In that case, $menu look like I described it, and You declare function like that:
function generate_menu_html($menu) {
// your menu generation function base on menu array
}
Hope it helps.
Best regards.
I think you shouldn't store html-code in a function. Normally you store these in seperate files and then inlude them.
for example:
require '/menu.php'
Then you would be able to add to each line
<li><?php if($pid == 1): ?> class='active'<?php endif; ?><a>...</a></li>
You can try something like this
$menu = '<ul class="nav navbar-nav">';
$menu .= '<li';
$menu .= ($pid==1)?' class="active"':'';
$menu .= '><a href="?pid=1">HOME ....REST OF THE CODES';
Related
I saw a few tutorial about this problem but none of them satisfied me. I want to highlight the single element of my list which matches the page that I'm browsing. I created the code with php, is a wordpress based website, and the code actually works because when I echo the uri which I'm on it will display the right uri, but the if statement I created to add a class when I'm on the website won't output anything.. and I don't understand why.. anyway.. here's the code:
header.php
<ul class="nav nav-pills sliding" id="Jcollapse">
<li class="<?php if ($current == "/why-chickapea/"){ echo "current";}?>"><span>Why Chickapea?</span></li>
<li class="<?php if ($current == "/our-pasta/"){ echo "current";}?>"><span>Our story</span></li>
<li class="<?php if ($current == "/shop-chickapea/"){ echo "current";}?>"><span>Shop</span></li>
<li class="<?php if ($current == "/recipes/"){ echo "current";}?>"><span>Recipes</span></li>
<li class="<?php if ($current == "/blog/"){ echo "current";}?>"><span>Blog</span></li>
</ul>
In each page I added a php snippet:
<?php $current = $_SERVER["REQUEST_URI"]; ?>
If I echo the var $current I will obtain the right url in this format: /pagename/
At the end I style the class current with a yellow color
.current {
color:yellow;
}
.current a {
color:yellow;
}
Does anyone know where my mistake is?
this is the page website: choosechickapea.com
As you can see the class that my code will generate is empty, but if I echo each value the uri I will obtain is the right one
The simplest explanation would be, that you print the header before $current is set.
The second simplest explanation is different scopes, meaning either you set $current in a non-global scope or you read it in a non-global scope, and those two (whatever they are) are different. Since someone said wordpress, I guess there is some encapsulation into functions (thus changing the scope). Using the global keyword may be a solution, but a dirty one. But since you're already avoiding wordpress functions ...
The actual code is:
Before declaring in the header the if statement, SET the value of the variable. If you'll declare in the body, even before loading the header with a, for example require once or in wordpress:
<?php get_header(); ?>
It won't work, the variable has to be set in the header like this:
<?php $current = $_SERVER["REQUEST_URI"]; ?>
<header class="navbar-fixed-top">
<ul class="nav nav-pills sliding">
<li class="<?php if ($current == "/your-url/"){ echo "current";}?>"><span>your url</span></li>
<li class="<?php if ($current == "/other-url/"){ echo "current";}?>"><span>/other url/</span></li>
</ul>
</header>
Hello how do you add php into an unordered list like below ?
<?php // Render the Category List
categoriesList(); ?>
<?php
into
<ul class="oi_smalldev_categories_list">
<li class="cat-item cat-item-7">
Coding
</ul>
Thank you.
This should work:
<ul>
<?php
$mycats = categoriesList();
foreach ($mycats as $cat) {
echo '<li>'. $cat. '</li>';
}
?>
</ul>
I'm guessing you want to take the results from the function and add them to your unordered list.
Basically, in your function you can create a string that is the HTML you want to output. In this case multiple tags.
You can then store it in a variable and call it with PHP further down the page.
Not the best way to handle it but I think this can do what you're after.
So, here's some pseudo code to handle that.
<?php // Render the Category List
$results = categoriesList();
?>
function categoriesList(){
return '<li>'.'category1'.'</li>'.'<li>'.'category2'.'</li>'.'<li>'.'category3'.'</li>';
}
<ul class="oi_smalldev_categories_list">
<?php echo $results; ?>
</ul>
This is my first question.
I'm building a simple dynamic menu using <li>
I'm working on a PHP based CMS (Kirby)
Kirby has predefined PHP functions (helpers)
I'm trying to output a <li> for each page on the website:
<li class='active'><a href='page1'></a></li>
<li><a href='page2'></a></li>
<li><a href='page3'></a></li>
...
Im using a PHP function e($condition, $value) to style the menu item only if that page isOpen()
// I need help here
<?php
foreach ($pages->visible() as $p):
echo "<li" . e($p->isOpen(), ' class="active"') . "><a href='" . $p->url() . "'></a></li>";
endforeach;
?>
The function is working but the css part class="active" is printing OUTSIDE the <li> on the final code
class="active"
<li>...</li>
<li>...</li>
<li>...</li>
I had this previous code that worked fine, but since i'm using display: inline-block the menu had spaces betwes each block, since the following code was placing each <li>in a new line.
// This code works
<?php foreach($pages->visible() as $p): ?>
<li <?php e($p->isOpen(), ' class="active"') ?> ></li>
<?php endforeach ?>
The reason i'm rewrinting the code is to remove the white space between the inline: blockelements.
I'm failing to concatenate the string in a way that the function works and print its results inside the <li>tag.
I've searched here and also have read lots of Docs in php.net but nothing worked to me, I'm struggling with this for 2 days.
I'm expecting to learn better how and when to use concatenation and string operators.
The problem is that Kirby's e() function already has the echo in the routine, instead of just simply returning the value.
http://getkirby.com/docs/cheatsheet/helpers/e
If you were to change your output loop to something more like this, echoing separately, you'll get the results in the desired order:
foreach($pages->visible() as $p)
{
echo "<li";
e($p->isOpen(), ' class="active"');
echo "> and the rest of your line </li>";
}
That said, perhaps using e() isn't the most elegant in this case. Maybe try the r() function instead:
http://getkirby.com/docs/cheatsheet/helpers/r
foreach($pages->visible() as $p)
{
echo "<li ".r($p->isOpen(), ' class="active"').">more text</li>";
}
I am developing a website using PHP and this is the 1st time I am trying a dynamic menu.
What I am doing is I have created a table for pages.
The table structure is as follows:
____________________________________________________________________________
|page_id|title|url|content|menu_title|show_on_navuigation|is_sub|parent_page|
|_______|_____|___|_______|__________|___________________|______|___________|
Here is_sub indicates whether it is a dropdown menu of some main menu. and parent_page is the main menu of the sub menu.
Now, what I want is, like
I have created 2 parent pages:
About Us and Test
and 2 sub menu's: Test aboutus and testsub,
Test aboutus is sub of About Us and testsub is sub of test.
How actually should the query and the loop, so that the menu renders perfectly.
Thanks in advance.
This is my menu structure:
<ul>
<li class='has-sub'><a href='#'><span>About Us</span></a>
<ul>
<li><a href='corporateprofile'><span>Corporate Profile</span></a></li>
<li class='last'><a href='visionandmission'><span>Vision & Mission</span></a></li>
</ul>
</li>
<li class='has-sub'><a href='#'><span>Business Services</span></a>
<ul>
<li><a href='recruitment'><span>Recruitment</span></a></li>
<li><a href='training'><span>Training</span></a></li>
<li><a href='executivesearch'><span>Executive Search</span></a></li>
<li><a href='payroll'><span>Payroll</span></a></li>
<li class='last'><a href='backgroundverification'><span>Background Verification</span></a></li>
</ul>
</li>
<li class='has-sub'><a href='#'><span>Employers</span></a>
<ul>
<li><a href='enquiry'><span>Enquiry</span></a></li>
<li><a href='jobdescription'><span>Job Description</span></a></li>
<li><a href='employercontract'><span>Employer Contract</span></a></li>
<li class='last'><a href='feedback'><span>Feedback</span></a></li>
</ul>
</li>
<li class='has-sub'><a href='javascript:;'><span>Job Seeker</span></a>
<ul>
<li><a href='applyforjob'><span>Apply For Job/Register</span></a></li>
<li><a href='careertips'><span>Career Tips</span></a></li>
<li><a href='interview Questions'><span>Interview Questions</span></a></li>
<li><a href='interviewprocess'><span>Interview Process</span></a></li>
<li class='last'><a href='corporatedress'><span>Corporate Dress</span></a></li>
</ul>
</li>
<li class='has-sub'><a href='#'><span>Franchise</span></a>
<ul>
<li class='last'><a href='#'><span>Franchise Enquiry Form</span></a></li>
</ul>
</li>
<li class='last'><a href='#'><span>Contact us</span></a></li>
</ul>
<?php
function displayMenu($parent_page_id) {
$sql = "SELECT * FROM `pages` WHERE `parent_page` = '$parent_page_id'"; // sql
$result = mysql_query($sql);
if( mysql_num_rows($result) === 0 ) { // mysql_num_rows() is deprecated, but you are using mysql extension so that's why I show it here
return true; // exit function
} // else, continue to rest of function
echo '<ul>';
while($row = mysql_fetch_assoc($result)) { // deprecated mysql php function here for simplicity
echo '<li>' . $result['menu_title'] . ''; // no closing </li> yet
displayMenu($row['page_id']); // this is the recursive part
echo '</li>'; // close the <li> from before the recursion
}
echo '</ul>';
}
$get_base_menu = mysql_query("SELECT * FROM pages WHERE parent_page = 0");
while($fetch_base_menu = mysql_fetch_array($get_base_menu))
{
$parent_page_id = $fetch_base_menu['page_id'];
displayMenu($parent_page_id);
}
?>
I highly suggest trying to get away from using an Adjacency List model and move toward a much easier to manage solution, such as a nested set. Using an MPTT type solution should help you manage your hierarchical data much easier. Using an Adjacency List model you are limited at a certain point.
I'd suggest looking into using something along the lines of Zebra_MPTT, or some other form of MPTT library. Please checkout this article on Managing Hierarchical data in MySQL.
I think the simplest thing for you to code will be something like this recursive function. All you have to do is put it on your page and make sure you have parent_page_id = 0 for the base level menu items. (I'm using parent_page_id instead of parent_page because I assume that is what you mean and it is more clear for the answer.)
Calling the function with an argument of "0" should give you the full menu tree.
$trace = array();
function displayMenu($parent_page_id) {
$sql = "SELECT * FROM `tbl_menu` WHERE `parent_page_id` = $parent_page_id"; // sql
$result = mysql_query($sql);
if( mysql_num_rows($result) === 0 ) { // mysql_num_rows() is deprecated, but you are using mysql extension so that's why I show it here
$trace[] = "Page_id $parent_page_id has no children";
return true; // exit function
} // else, continue to rest of function
echo '<ul>';
while($row = mysql_fetch_assoc($result)) { // deprecated mysql php function here for simplicity
$trace[] = "Entered while loop for page_id = $parent_page_id"; // not an error, just tracking
echo '<li>' . $row['menu_title'] . ''; // no closing </li> yet
displayMenu($row['page_id']); // this is the recursive part
echo '</li>'; // close the <li> from before the recursion
}
echo '</ul>';
}
displayMenu(0); // call function for base level
var_dump($trace);
More info:
I have researched the topic before and had a nice link to a page on mysql.com with an in-depth exploration of hierarchical relational database structures. But when I checked, the link was broken!
But, I think I found it on another site, here:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
So I have this code that detects what page the user is on and then spits out a class of "active" if necessary.
<li <?php if (stripos($_SERVER['REQUEST_URI'],'index.php') {echo 'class="active"';} ?>>
So just to clarify, this code checks if the url has index.php in it, and if it does, it spits out the "active" class. What I need to do and don't know how to is add multiple instances to this code. So instead of just detecting index.php it needs to be able to detect other pages like about.php for example.
Sorry if this comes a very simple question to most of you but I am new to PHP.
Split your code from the layout.
Possible solution:
<?php
$active_flags = array('index.php','about.php','test.php');
$active = '';
foreach($active_flags as $item) {
if(stripos($_SERVER['REQUEST_URI'],$item)!==false) {
$active='active';
break;
}
}
?>
<li class="<?php echo $active?>">Your list Item</li>
As you are listing manually you just enter this one it really help you
<li
if(strpos($_SERVER['REQUEST_URI'],'index.php'))
{
echo 'class="active"';
}
else
{
echo 'class="inactive"';
}
</li>