I’m fairly new to web-centric design and programming.
I’ve got a HTML + CSS with PHP page I’m quite happy with. It’s got a header, a main content area, and a sidebar.
Now I’m working on my second page. The second page should have the same look as the first page. I’ll reuse the CSS, but there seems to be a lot of repetition between the first and second pages (the content in the header, and the sidebar, for example, is almost identical).
Is it normal to repeat things over multiple pages? If, later, I want to change something, I’m going to have to change it in (potentially) numerous places; that seems rather silly, so I presume I’m missing something.
I thought perhaps I’d use the “small parts” from my CSS in a “larger” wrapper, encompassing the entire Header, perhaps, and then include that in both pages; I’m not sure if that’s the right direction I should be heading (or how I’d do it).
I also thought perhaps I could use PHP to dynamically generate the page each time, wrap the generation in a class, and then end up with something like myClass->generateHeader(). I’m using PHP to generate some of the page anyway, so the conceptional leap isn’t too great; on the other hand, I imagine that generating the page each request is worse in terms of performance, and (from my brief searching) seems to involve several hundred lines of PHP to generate a rather short stretch of HTML, (assuming it’s anything more complicated than a bunch of echo statements containing the HTML I’d have written anyway.
Searching for “creating HTML templates” is rather fruitless, but I’m not sure what kind of keywords I’d be using to ask how this is normally handled.
How do you adhere to DRY and avoid repeating yourself over several related pages in a website?
You can use the php include method: http://php.net/manual/en/function.include.php in order to not have to repeat parts of your page that are always needed. For example, the header and footer, navigation, etc..
To answer your other question, using a class to store html sections is another way to go and can prove to be useful. It also won’t add a lot of extra processing time unless your class needs to do a lot of calculations upon initialization.