• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

90
Vistas
Render Nunjucks macro in AJAX call on client side?

I am trying to render data from a JSON file on the front end using AJAX (I am also using Eleventy, Nunjucks, and jQuery), and it would save a lot of headache + time to be able to use a Nunjucks macro (which I have already created) to render the information being returned instead of recreating the entire component (it would save future time and effort too as the code used wouldn't have to be edited twice).

Here is the code for that is creating the JSON data:

// AJAX Call for Posts
config.addCollection("post", async function (collectionApi) {

    // get unsorted items 
    let allPosts = await collectionApi.getFilteredByTag("post");

    // Loop through and only get the data you need from each post 
    let curatedPostData = allPosts.map(post => {
        return {
            title: post.data.title,
            description: post.data.description,
            image: post.data.image,
            url: post.url
        }
    });

    // Filter out any null values 
    curatedPostData = curatedPostData.filter(post => post);

    // Create a new file in your project 
    fs.writeFileSync("_data/ajax-list.json", JSON.stringify(curatedPostData))
});

Ideally, this would work for the AJAX call but it is not currently:

$("#showMorePostsButton").click(function(){
  $.ajax({url: "/js/posts-list.json", success: function(result){

    // Output results from AJAX call
    $("#displayPosts").html( 

    // Import the Nunjucks macro
    {% from 'components/cards/postCard.njk' import postCard %}

    // Use the macro with information from AJAX call
    {{ postCard(postTitle = title, postDescription = description, postImage = image) }}
    );

  }});
});

Would anyone know how to get this snippet working and use a Nunjucks macro on the frontend somehow with Eleventy, Javascript, or Nunjucks itself?

Any and all suggestions are very much appreciated, thanks

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use js data files to load data from your api.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda