Search code examples
javascripthtmlcssautomationcode-generation

How can I automatically generate a html contents page and on-page links to the next and previous page with names?


I am writing an online non-fiction history book. To keep it simple, it is about ancient empires etc. I have written the whole thing manually in html and css. I have a table of contents page with links to every page. On each page there is a link forward and back with the title of the respective page. These have all been done manually. My problem is that reorganization or insertion or deletion is time-consuming and error-prone. Let's say I have pages for Egypt, Greece, and Rome. I decide to insert Babylon between Egypt and Greece. I must modify the contents page and the links on Egypt and Greece. If I later rename Greece to Hellas, I must modify the the title everywhere again.

What I need is a system where I can name each page and drag and drop them in the order I want and everything will be generated automatically.


Solution

  • To keep it really simple I would have a JS file which holds the index as an array - and make that the only place this sequence is held.

    Include it in the head of each of your html files with a script tag

    const index =['Egypt', 'Greece', 'Rome'];
    const name = window.location.href.split('/').at(-1).split('.')[0];
    const i = index.indexOf(name);
    const prevName = (i > 0) ? index[i - 1] : '';
    const nextName = (i < (index.length - 1)) ? index[i + 1] : '';
    

    The JS in each of your HTML files can then use the consts to either create the forward and back buttons or, in the case of the actual contents page, use the index array.

    It's so simple that I wouldn't bother creating a drag and drop interface.