简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM