Go HTML Template Active Nav-Link Bootstrap

In the provided HTML code snippet, it appears to be a part of a Bootstrap navigation menu that is using Go’s HTML template syntax to conditionally add the “active” class to a navigation link based on a condition. In this case, it is checking whether the current page’s title is equal to “Home” and adding the “active” class if the condition is true.

Let me break down the code for you:

  1. <li class="nav-item">: This is an HTML list item element with the class “nav-item.” It is typically used for a navigation menu item.

  2. <a class="nav-link {{if (eq .title "Home")}}active{{end}}" href="/groups">Groups</a>: This is a hyperlink (<a>) element with the class “nav-link” for styling purposes. The {{if (eq .title "Home")}}active{{end}} part is using Go’s template syntax to conditionally add the “active” class to the anchor element based on a condition.

    • {{if (eq .title "Home")}}: This part starts an if statement in Go’s template syntax.
    • (eq .title "Home"): This is the condition being checked. It compares the value of .title (a variable or data available in the template) to the string “Home” using the eq function. If they are equal, the condition is true.
    • active: If the condition is true, “active” is added to the class attribute of the anchor element.
    • {{end}}: This marks the end of the if statement.

So, if the value of .title is “Home,” the resulting HTML will look like this:

1
2
3
<li class="nav-item">
    <a class="nav-link active" href="/groups">Groups</a>
</li>

Otherwise, if the value of .title is not “Home,” the “active” class will not be added to the anchor element, and it will look like this:

1
2
3
<li class="nav-item">
    <a class="nav-link" href="/groups">Groups</a>
</li>

This technique is commonly used to highlight the currently active page in a navigation menu by applying specific styling (in this case, the “active” class) to the corresponding menu item.

0%