0

I've recently been trying to get to grips with nunjucks, I've used handlebars before so the learning curve hasn't been that bad. However there is one thing I can't seem to get working:

I've got a JSON file which has the following data in it:

"contentIntro" : {
    "componentClass" : "c-global-header",
    "title" : "Welcome Firstname Surname,",
    "subtitle" : "New applications:",
    "bodyCopy" : "You can create, edit and save the draft application as many times as you need before submitting it for assessment.",
    "ctaType" : "text",
    "ctaText" : "View the list",
    "ctaURL" : "#"
  }

This exists in a JSON file which includes other page elements but it's only the contentIntro context I'm interested in.

If I include a partial like this:

{% include "components/c-headed-text.nunjucks" %}

then I can access the JSON data using dot notation within that partial (eg {{ contentIntro.title }}), however this isn't very flexible and it precludes me having more than one of the same partial type on the page.

Ideally what I'd want to do is import the partial like this:

{% import "components/c-headed-text.nunjucks" as contentIntro %}

and then in the template I can just access the JSON data using {{ title }} as it will already know the context from the import.

Annoyingly though it doesn't work and I can't see why. The Jinja2 documentation seems to suggest it would but I can't get it to work using Nunjucks, is this even possible?

Edit: I should also add that the templates are being prerendered in gulp so the end result is just flat HTML.

Alex Foxleigh
  • 1,784
  • 2
  • 21
  • 47

1 Answers1

2

Ok I've found a way around it. it's not as clean as I'd like but it does the job.

I just a normal include statement:

{% include "components/c-headed-text.nunjucks" %}

but above it a set a variable as follows:

{% set context = contentIntro %}

Then inside the partial I can just use {{ context.title }} and it works like a charm!

Alex Foxleigh
  • 1,784
  • 2
  • 21
  • 47