Split html source into multiple files

You can't, at least not in flat-HTML. What you can do is using Javascript to load and place the snippets. iframes are also non-ideal because contrary to what happens with directives like #include and partial, those snippets will never be compiled in one single page.

However, I think it's important here to understand how your pages will be served. Is this a static website? Because in this case I would write a simple script in your language of choice to compile the page. Let's say that you have a base like this:

<html>
    <head>
        <!-- ... -->
    </head>

    <body>
        {{ parts/navigation.html }}
        <!-- ... -->
    </body>
</html>

You could write a script that runs through this file line by line and loads the content into a variable named, for example, compiled_html. When it finds {{ file }} it opens file, reads its content and append it to compiled_html. When it gets to the end, it writes the content of the variable into a HTML file. How you would implement it depends on the languages you know. I'm sure that it's pretty straightforward to do it in C#.

This way you'll be able to split the source of your HTML pages into multiple files (and reuse some parts if you need them), but you'll still end up with fully functional single files.


It is easily possible, if you are running PHP:

The PHP Language has the "include" command built in. Therefore you can have your "index.php" (note you have to change the suffix, for the PHP parser to kick-in) and simply use following syntax.

<html>
  <head>
    [...] (header content you want to set or use)
  </head>
  <body>
    <?php
      include "relative/path/to/your/firstfile.html";
      include "relative/path/to/your/secondfile.html";
      include "relative/path/to/your/evenwithothersuffix/thirdfile.php";
      include "relative/path/to/your/fourth/file/in/another/folder.html";
    ?>
    [...] (other source code you whish to use in the HTML body part)
  </body>
</html>

Basically making you main index.php file a container-file and the included html files the components, which you like to maintain seperately.

For further reading I recommend the PHP Manual and the W3Schools Include Page.


not possible with static html.

in general, this problem (lazy-fetching of content) is solved with a template processor.

two options:

  1. template processor runs on the server side
    • any language
    • static website generators, server side rendering
  2. template processor runs on the client side
    • javascript
    • web frameworks

Tags:

Html