简体   繁体   English

在客户端的 AJAX 调用中渲染 Nunjucks 宏?

[英]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).我正在尝试使用 AJAX 在前端渲染来自 JSON 文件的数据(我也在使用 Eleventy、Nunjucks 和 jQuery),这样可以节省很多头痛和时间来使用 Nunjucks 宏(我已经创建)来呈现返回的信息而不是重新创建整个组件(这也将节省未来的时间和精力,因为所使用的代码不必被编辑两次)。

Here is the code for that is creating the JSON data:这是创建 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))
});

Ideally, this would work for the AJAX call but it is not currently:理想情况下,这适用于 AJAX 调用,但目前不是:

$("#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.您可以使用js 数据文件从您的 api 加载数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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