Mayank_17
Mayank_17

Reputation: 75

Make bootstrap link active in php

My navbar has links which are active according to the base URL of the current page.

PHP Function :

function Match($requestUri){

    $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");

    if ($current_file_name == $requestUri) 
        return "active";
    }

Link:

echo "<li class=".Match("cms").'nav-item'."><a href='/cms/index.php'>Home</a>"

What I am getting:

<li class="activenav-item"><a href="/cms/index.php">Home</a></li>

What Should be:

<li class="active nav-item"><a href="/cms/index.php">Home</a></li>

What should I do to add whitespace after active?

Upvotes: 0

Views: 70

Answers (2)

Zsw
Zsw

Reputation: 4107

As a fair alternative, you can also include the space in your return statement.

if ($current_file_name == $requestUri) 
    return "active ";
}

However, are you sure that you're actually getting the result you think you're getting? This line here is not quoted correctly.

echo "<li class=".Match("cms").'nav-item'."><a href='/cms/index.php'>Home</a>"

You should quote it as such:

echo "<li class='".Match("cms")."nav-item'><a href='/cms/index.php'>Home</a>";

Upvotes: 1

Glorfindel
Glorfindel

Reputation: 22651

You can just include the space inside the string literal:

echo "<li class='".Match("cms")." nav-item'><a href='/cms/index.php'>Home</a>"
                                 ^

Even if Match would return an empty string, this would be valid HTML - the leading space is then just ignored by the browser.

Note that you are also mixing up single and double quotes. If you construct a piece of HTML like this, it is best to use double quotes for PHP string delimiters, and single quotes for HTML attributes (as this allows for variable parsing).

Upvotes: 3

Related Questions