Nested includes with passed data in nunjucks

55 Views Asked by At

In react, I would pass props down to a template. How do I do this in nunjucks. For example, I want to do the following:

Page:

{% set slides = [
  { "alt": "Tokenization Visualization","title": "Tokenization", "description": "The LLM starts by breaking down the input text, or 'prompt', into smaller pieces known as tokens.", "image": "/img/ai/carousels/how-llm-works/tokenization.png"},
  { "alt": "Embedding Visualization","title": "Embedding", "description": "Next, each token is converted into a numerical representation through a process called embedding.", "image": "/img/ai/carousels/how-llm-works/embedding.png"},
  { "alt": "Self-attention Visualization","title": "Self-attention", "description": "The model then adds additional information to these vectors to account for the order of words in the input. Self attention mechanisms allow the model to create context-aware representations of each word.", "image": "/img/ai/carousels/how-llm-works/self-attention.png"},
  { "alt": "Decoding Visualization","title": "Decoding", "description": "The LLM Decoder will take the output and use it to predict the next token in the sequence.", "image": "/img/ai/carousels/how-llm-works/decoding.png"},
  { "alt": "Output Visualization","title": "Output", "description": "Finally, the model generates a response.", "image": "/img/ai/carousels/how-llm-works/output.png"}
]
%}

{% include "partials/image-cards/image-cards.html" with { slides: slides } %}

Image-cards:

<div class="image-cards flex flex-wrap justify-between py-6 ff-inter">
  {% for slide in slides %}
    {% include "partials/image-cards/image-card.html" with { slide: slide, index: loop.index} %}
  {% endfor %}
</div>

Image-card:

<div id="item{{index}}" class="card card-compact w-full md:w-[45%] shrink-0 grow-0s mt-10">
  <figure class="card-figure !mt-0 !mb-0">
      <img src="{{ slide.image }}" alt="{{slide.alt}}" class="w-full" />
  </figure>
  <div class="card-body !px-0 text-primary-content whitespace-normal">
      <div class="font-semibold mb-0">{{ slide.title }}</div>
      <p>{{ slide.description }}</p>
  </div>
</div>

This currently breaks, indicating:

Template render error: (/paget.html) [Line 24, Column 57]. expected block end in include statement

1

There are 1 best solutions below

0
Aikon Mogwai On

Nunjucks doesn't support with-clause. You can use Environment.render to implement own include

// index.js
const nunjucks  = require('nunjucks')
const env = nunjucks.configure()
env.addFilter('render', (template, ctx) => env.filters.safe(env.render(template, ctx)))

var html = env.renderString(`{{ 'test.njk' | render({a: 10, b: 100}) }}`)
console.log(html)
// test.njk
a: {{ a }}, b: {{ b }} 
{{ 'test2.njk' | render ({a: a + 10, b: b + 10}) }}
// test2.njk
a: {{ a }}, b: {{b}} 

It can be extended with an async loader. But render doesn't work with macro-clause.