harttle / liquidjs

A simple, expressive, safe and Shopify compatible template engine in pure JavaScript.
https://liquidjs.com
MIT License
1.52k stars 238 forks source link

Asynchronous data fetching while assigning #636

Closed AsadCSE closed 1 year ago

AsadCSE commented 1 year ago

Hello, firstly i'm new to templating, I was wondering if dynamic handles could be passed to fetch objects asynchronously from database before rendering. Like in the example:

{% assign featured_product = all_products['product_handle'] %}

if 'all_products' be global asynchronous function which fetches 'product_handle' and passes the data for parsing and rendering, how to do that? can you help?

harttle commented 1 year ago

I believe this is properly addressed in #638, for record, here's a runnable sample code in case anyone need it.

const { Liquid, Drop } = require('liquidjs');

class MyDrop extends Drop {
   async product_handle(){
      return "PRODUCT"
   }
}

(async function() {
   const engine = new Liquid()
   const template = `
   {% assign featured_product = all_products['product_handle'] %}
   {{ featured_product }}
`
   const data = {
      all_products: new MyDrop()
   }
   const html = await engine.parseAndRender(template, data)
   console.log(html)
})()