0

When creating a webpage, we often include the nav on all pages:

<nav id="nav">
    <ul>
        <li><a href="about.html" class="active">About us</a></li>
        <li><a href="services.html">Services</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
</nav>

We'll often only mark the active page by using an active class:

<li><a href="contact.html" class="active">Contact</a></li>

Copying-and-pasting the whole navigation into all subpages is not a good idea - if we decide to add one new page, we have to change the nav on all subpages.

Can we put the navigation into a separate file and then import it?

<!-- PSEUDOCODE --> <import file="nav.html" active="About us" />

Or maybe there is a HTML-compliant preprocessor for this (I want to reuse my existing code, not rewrite it from scratch)

marmistrz
  • 5,974
  • 10
  • 42
  • 94
  • 2
    Possible duplicate of [Include another HTML file in a HTML file](http://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file) or google for "html template engine" – JJJ Jul 28 '16 at 11:21

1 Answers1

1

You have a few options on how to do this, and as always, each one has it's pros and cons ...

1 - Use a single Html file. This might sound crazy at first, but depending on how much data your site have, it might be a good and easy solution. But it obviously don't scale well and you might end up with a huge file.

2 - Use a <frame> or a <iframe> tag. This is the oldest way to do it and it's very easy to implement, but it has some problems with SEF, bookmarks and print.

3 - Use Ajax (XMLHttpRequest) to load an external Html with Javascript. This is also relatively easy to implement, but it has some problems with navigation ('back' button) and rely on javascript.

5 - Use a server side template engine. This can require some effort depending on your server structure, but it's not a very hard thing to do. The cons here are that you might have some extra work to adjust your files the template engine.

You could also use sockets to fetch your data but this feels like using a screwdriver to hammer a nail.

rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63