Leveraging gulp-data to incorporate JSON data into Nunjucks templating

I am looking to incorporate JSON data into nunjucks "set". Here's a simple example:

index.html

{% set divname='foo' %}
{% include 'template.nunjucks' %}

template.nunjucks

<div class="{{divname}}"></div>

Everything works smoothly. However, I want to separate the data, like the divname, from the index.html file and place it into a JSON file named data.json:

{
"div_name": "foo"
}

By using gulp-data, we can fetch the data from data.json and use {{div_name}} almost anywhere in index.html..almost. It seems that using {{div_name}} inside nunjucks content is not achievable, probably due to nested { ?

{% set divname='{{div_name}}' %}

Unable to retrieve the JSON data, the output is

<div class="{{divname}}"></div>   instead of   <div class="foo"></div>

The reason behind this requirement is so that in data.json, I can define multiple divnames (divname1=foo, divname2=bar, divname3=ball) and reuse template.nunjucks. This approach becomes handy when the markup in template.nunjucks or index.html gets complex, allowing the utilization of templating engines efficiently. A practical scenario is a lengthy/semi-complicated AWS CloudFormation template where resource names are employed in various instances, and different data.json files are used for dev and prod environments. Shifting values to dev-data.json and prod-data.json while keeping only one "index" file for infrastructure definition, which pulls in templates will streamline maintenance

{% set divname={{divname1}} %}
{% include 'template.nunjucks' %}
{% set divname={{divname2}} %}
{% include 'template.nunjucks' %}

dev-data.json

divname1 = dev-foo
divname2 = dev-bar

prod-data.json

divname1 = foo
divname2 = bar

There you have it, different data for dev and prod environments using a single index.html file for maintenance

Answer №1

Haven't had the opportunity to work with nunjucks before, but it seems like you could simply remove the brackets around title_data in the set statement: {% set title = title_data %}.

However, if you already have the title string, there's no need to reassign it. You can just directly template it like this:

<title>{{ title_data }}</title>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hybrid component that combines static and dynamic elements in Gatsby

The inconsistency in behavior between the site generated by gatsby develop and gatsby build is causing an issue where the site works during development but not when it's in production. An overview of my website: My website is a simple blog-like plat ...

The client sent a risky Request.Path value that raised red flags

For a university project, I am attempting to access an English translation of the Quran from quran.com using the provided link: Although this link works correctly when entered directly into a browser, I encounter an error when trying to use it in my Angul ...

When attempting to duplicate a project from Bitbucket and working in VS Code, I encountered several errors and warnings while running npm install

I have a project on Bitbucket that I'm trying to clone. The project is quite old, about 3 years old, so some packages may be outdated. However, when I run npm install, I am seeing a lot of warnings and errors. Additionally, the project was originally ...

Tips on effectively parsing a JSON string in a React Native application

I stored all the information in asyncStorage as a string, and then attempted to parse it. When I check the console log, this is what I see: "{\"metadata\":{\"lastSignInTime\":1610728860334,\"creationT ...

Why is $scope.$watch('$destroy') being called in Angular UI Router 1.0 even when not leaving the state?

Take a look at the plunker here. My understanding is that $scope.$watch('$destroy') should be invoked when $scope is on the verge of being destroyed. In the provided example, it seems that upon entering a state, the $scope.$watch('$destroy ...

How can I implement user-specific changes using Flask?

I am a beginner with Flask and I am working on a project where users can sign up, and if the admin clicks a button next to their name, the user's homepage will change. Below is the Flask code snippet: from flask import Flask, redirect, url_for, render ...

Welcome Message using Discord.js V13

As a newcomer to bot creation, I am facing an issue with my welcome message in discord.js v13. Previously working in v12, I am now encountering difficulties sending a message to a specific channel when a user joins the server. After some investigation, I r ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

not capable of outputting findings in a sequential manner

I am encountering an issue where my result is not printing line by line, instead everything shows up on a single line. How can I resolve this problem? Here is the code snippet I have tried: <script> function know(){ var num = Number(doc ...

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

Tips for adjusting column width with flexbox intersections

I am currently working on a React web application that has minimal styling. I have divided the content into 3 columns, with the leftWrap being col-3, rightWrap being col-4, and the remaining width is for centerWrap. I want to apply flex ...

How can I update two divs simultaneously with just one ajax call?

Is there a way to update 2 divs using only one ajax request? The code for updating through ajax is in ajax-update.php. <?php include("config.inc.php"); include("user.inc.php"); $id = $_GET['id']; $item = New item($id); $result = $item->it ...

I have a task of initiating a request from JavaScript to a PHP file using an API

Seeking assistance! I have two php files named Data.php and Status.php. The task is to send a request to Data.php when data is entered in the zip field, and if the zip code is valid, then send the data to Status.php for parsing the response. Below you will ...