Repeat HTML code among pages of a project
Hey I am just wondering, is there any way that when I create the header for a project, it will be repeated to every page then without copy/paste. And when I change the initial header all of them will be adjusted.
I am refering to the HTML code of the header 🙂
Thank you!
9 Replies
If you are working with bare HTML, it's not possible. You need to use a templating language or tooling of some sort depending on what you're trying to make.
There are static site generators that you can use but I'm not entirely familiar with them. Astro is one popular choice for making websites and it scales pretty decently.
You may be interested in using other type of solutions like WordPress, it just depends on what you want to make.
or just like in the old days, use <iframes>
(just kidding, do NOT do that)
Really old-school: https://httpd.apache.org/docs/current/howto/ssi.html
Also, really, really don't do that
use something like Astro or some template language like Joao suggested
I usually use php for this.
So in my index.php file, i have this
And in body.php, i have this
So let's say you have a pages folder with a file called register.php you can go to 127.0.0.1/?p=register to see your register page, and the head and navbar and footer will be included in each page that is inside your pages folder.
I am not sure if this is the best way to do it, but it's working at least
With modern technology I just use an image for my header, it's as simple to add as
As long as you don't need multiple buttons it's all good
(I too should clarify this is a joke, can't bee too cautious)
I like this approach, with the only downside that you require a server in place. If there's no need for computing anything on the backend (authentication, CRUD operations, etc) then I would prefer to use a static site generator. We would need OP to specify this.
Websites are generally made using some kind of framework whether it's a static framework like Astro, or a JavaScript framework like Angular or Svelte, or server rendered like PHP or Next.js. Go Astro if you don't need the features of JavaScript frameworks, feel free to use some JavaScript, it doesn't have to be entirely static, going the PHP route may work best if you need the server side code (as much as people badmouth PHP, it's not actually bad).
This solves the problem super easily, and it also reduces code duplication for more than just headers. It's uncommon for websites to be made with just plain HTML, CSS, and JS without any tooling.
This is true yeah 🙂
yeah great suggestions, thank you very much
will check Astro solution for sure