HTML redundancy in navigation
-
28-06-2021 - |
Question
Coming from C++ I was taught that code repetition is a giant red flag of doing something wrong. Now when I make a navigation menu in HTML I have to copy it into each page I want it in, violating everything I've known about clean code. Is this just the way HTML will be or would it be cleaner to define the navigation menu in a separate HTML file and use an Iframe to display it into the pages?
Solution
I agree with your sentiment. It would be cleaner to put your navbar in a single html file, and load it separately. However, I would suggest you use some server-side script (like PHP) to put all the html together, rather than loading it in an iframe.
You can make a very simple PHP script that will concatenate html from several files, then output it to the browser. If this is possible in your case, that's what I would do.
OTHER TIPS
If you're just working on static html pages, use server side includes if you're able:
http://en.wikipedia.org/wiki/Server_Side_Includes
In a nutshell, define your code in a separate file, each template then just references that file wherever you tell it to.
There's a hundred and one different ways of 'including' a template style file in a page, just depends on what kind of setup your host has I guess.