Blog script help

Greetings to all!

I got a script to display the last 3 publications made in a section, it worked locally, but when loading the files it doesn’t work, I’ll explain what I did, pass on the codes and hope someone can find a solution.

I have the following files and folder in the root directory:

index.html, script.js and a folder called blog, where the following files are located:

  • 00001.html
  • 00002.html
  • 00003.html
  • 00004.html
  • 00005.html

The hierarchy is this:

root directory

  • blog folder
    – 00001.html
    – 00002.html
    – 00003.html
    – 00004.html
    – 00005.html
  • index.html
  • script.js

HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meu Blog</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <header class="bg-dark text-white text-center py-5">
        <h1>Meu Blog</h1>
    </header>
    <main class="container my-5">
        <div class="row" id="blog-posts">
            <!-- As postagens do blog serão carregadas aqui pelo JavaScript -->
        </div>
    </main>
    <!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

JS Code

document.addEventListener("DOMContentLoaded", function () {
    const blogPostsElement = document.getElementById("blog-posts");

    // Caminho para o diretório das postagens do blog
    const blogDirectory = "blog/";

    // Faz uma requisição AJAX para obter a lista de arquivos no diretório
    fetch(blogDirectory)
        .then((response) => response.text())
        .then((html) => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, "text/html");
            const fileLinks = Array.from(doc.querySelectorAll("a"))
                .map((link) => link.getAttribute("href"))
                .filter((href) => href.endsWith(".html")) // Filtra apenas arquivos HTML
                .sort(); // Ordena alfabeticamente (como texto)

            // Obtém os últimos 3 arquivos com base na ordem alfabética
            const lastThreeFiles = fileLinks.slice(-3).reverse(); // Inverte a ordem

            // Exibe as postagens
            lastThreeFiles.forEach((fileName) => {
                //const postUrl = blogDirectory + fileName;
                //const postUrl = fileName;
                const postUrl = fileName;

                // Carrega e exibe a postagem
                fetch(postUrl)
                    .then((response) => response.text())
                    .then((html) => {
                        const postElement = document.createElement("div");
                        postElement.classList.add("col-md-4");
                        postElement.innerHTML = html;
                        blogPostsElement.appendChild(postElement);
                    })
                    .catch((error) => {
                        console.error("Erro ao carregar a postagem:", error);
                    });
            });
        })
        .catch((error) => {
            console.error("Erro ao listar os arquivos do diretório:", error);
        });
});

Post template code

<div class="card">
  <img src="/assets/img/image.webp" class="card-img-top" alt="Imagem da Postagem 1">
  <div class="card-body">
    <h5 class="card-title">Title</h5>
    <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sed dui interdum justo
      rutrum sagittis. Vestibulum aliquam scelerisque metus, et congue dolor efficitur ac. Sed vel dui tincidunt dolor
      luctus rhoncus vel sed urna. Duis ut risus ex. Integer nec tellus libero. Vestibulum et turpis et justo viverra
      faucibus eu in velit. Nulla facilisi. Cras hendrerit condimentum congue. Aenean interdum lorem elit, vel
      sollicitudin sem consectetur et. Integer hendrerit ornare nisi at tristique. Cras vitae accumsan mi.</p>
  </div>
</div>

To work locally I changed the path to this

lastThreeFiles.forEach((fileName) => {
From this //const postUrl = blogDirectory + fileName;
For this //const postUrl = fileName;

I published it in a github repository, I published it as a bss.design site, but none of them worked.

If anyone knows a way to make it work it will help me solve part of a problem to have a blog system for static sites.

Astro build is a very good, It’s a piece of cake to make a static blog. There is also integration for cloudflare so it will be easy for you to deploy to cloudflare pages if you want.
have a look here

1 Like

Thank you very much, I’ll take a look.