Estoy tratando de representar datos de un archivo JSON en el front-end usando AJAX (también estoy usando Eleventy, Nunjucks y jQuery), y me ahorraría mucho dolor de cabeza + tiempo para poder usar una macro de Nunjucks (que yo ya han creado) para representar la información que se devuelve en lugar de recrear todo el componente (también ahorraría tiempo y esfuerzo en el futuro, ya que el código utilizado no tendría que editarse dos veces).
Aquí está el código para crear los datos JSON:
// 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)) });
Idealmente, esto funcionaría para la llamada AJAX, pero actualmente no lo es:
$("#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) }} ); }}); });
¿Alguien sabría cómo hacer que este fragmento funcione y usar una macro de Nunjucks en la interfaz de alguna manera con Eleventy, Javascript o Nunjucks?
Cualquier y todas las sugerencias son muy apreciadas, gracias
Puede usar archivos de datos js para cargar datos desde su API.