Reputation: 49
What is the best way to go about creating a navbar with HTML and CSS that is global to all pages and automatically highlights the active page? I'm using PHP and Symfony's templating engine, twig.
I was thinking I could create a navigation.json that the router could read from and then send to the template when it renders. Then on the template side of things, I could have it loop through the list of links and render them as html li item. Then when it go to the link that is the current page, it could add a class of "active". I'm not sure if this is the correct way to do it. I would really appreciate any suggestion you may have! Thanks
Here is my simple router I'm using.
<?php
include 'vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('static/templates/');
$twig = new \Twig\Environment($loader, []);
if (!isset($_GET['q'])) {
echo $twig->render('home.html');
} else if ($_GET['q'] == 'curriculum') {
echo $twig->render('curriculum.html');
} else {
echo $twig->render('404.html');
}
?>
And here is the base.html template that all other template extend.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{% block title %}{% endblock %}</title>
<!-- Favicon -->
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#4e9b4d">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
<!-- Font Awesome Icons-->
<script src="https://kit.fontawesome.com/e1c18cc05e.js" crossorigin="anonymous"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="static/styles/main.css" />
{% block head %}{% endblock %}
</head>
<body>
<header class="navbar">
<a class="content" href="/">
<img src="static/assets/logo.png" alt="Education Transformation Centre Logo"/>
</a>
</header>
{% block content %}{% endblock %}
<footer class="footer">
//footer content here
</footer>
</body>
</html>
Upvotes: 0
Views: 131
Reputation: 376
The best way, I think would be to use the current route directly in the navbar to set the link to enabled/disabled something like:
<li{% if app.request.get('_route') == '_myRoute' %} class="active"{% endif %}>
<a href="{{ path('_adminIndex') }}">Admin Home</a>
</li>
Upvotes: 1