Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!