How use JSON variable inside of pug template - json

I want to able create many identical blocks with different data. For exaple list of items with different names and values.
So I have a pug file like this:
- var data = require("data.json")
mixin item(name,val)
.item
.item-name= name
.item-val= val
mixin items(input)
each itm in input
+item(itm.name,itm.value)
+items(data)
And my JSON file data.json like this:
[
{
"name" : "item1",
"value": "100"
},
{
"name" : "item2",
"value": "200"
},
{
"name" : "item3",
"value": "500"
}
]
Also I want to load different json data and use it with my items mixin to build different blocks
But gulp didn't compile this code and throw error "write after end" on my pug file
I also added some code with "locals" for my gulp taks:
gulp.task('site:pug:pages', function() {
var settings = Config.getTaskSettings('site:pug:pages');
return gulp.src(BASE_PATH + settings.source)
// return gulp.src("./html/**/*.pug")
.pipe(plumber({
errorHandler: notify.onError()
}))
.pipe(pug({pretty: true,locals: {
require: require
}}))
.pipe(gulp.dest(DEST_PATH + settings.dist))
.pipe(global.browserSync.stream());
});
But this didn't help.
A know that I can pass json data from gulp task. But there are 2 issues:
I don't want to pass these json at gulp task because if I have new file I should write it at gulp task file.
This also didn't work and throw the same "write after end" error
Is there a easy way to use JSON data at pug templates

I'm using parcel to do the job.
First get the json file on the pug.config.js file(if you don`t know about this config file look here)
const dataFile = require("./data.json");
module.exports = {
locals: {
dataVariable: dataFile,
}
};
Then for exemple on a index.pug I use an each loop to display the ID's included in the someData array inside my JSON file:
each data in dataVariable.someData
li= data.ID
data.json file used.
{
"someData": [
{
"ID": "xrHLZ",
},
{
"ID": "ar23D",
}
]
}

Related

handling a well-formed JSON file of an array of objects

A JSON string string passes the jsonlint test.
response = [
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"7461221587662919569"
],
}
},
"text" : "where they would 'transfer to' next.",
"lang" : "en",
}
},
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"6613144915874808065"
],
}
},
"text" : "produto regional.",
"lang" : "pt"
}
}
]
However, after processing
require 'json'
file = File.read('/Users/main/jugg//article_samples.js')
data_hash = JSON.parse(file)
One is left with an array, whereas more frequently a hash with a name labels a subsequent array, where one works with that nomenclature such as response['data']
But in this case the array is not accessible via response[0]. How can this be considered as an array in order to process each individual element collection.each do |member|?
A curiosity: data_hash.class => NilClass
The response = ... code from article_samples.js is JavaScript, not JSON. This initializes a variable named response with a JavaScript array.
To use this as JSON, then rename the file to article_samples.json and remove response = from the file. The first line should start with [.
Now your second block of code should work just fine as long as the article_samples.json file is in the correct path.
On a side note, I suggest that you find a way to make the path more flexible. The way you have it currently hard coded is tied directly to your current machine's file system. This won't work if you want to run this code from another machine because the folder /Users/main/jugg probalby won't exist.
If this is a web server with ruby on rails, then one solution is to create an environment variable with the path where this file is stored.

How add terraform variables in a JSON file

Hey team I’m having trouble finding in the documentation on how to add terraform variables in a JSON file,
I need inject this variable in this JSON,
In this JSON of this shape but not it works,
I did try with var and locals, I tried it with var and locals, but it does not work, it is by default
You could use templatefile function [1]:
locals {
mystring = "Test"
}
resource "grafana_dashboard" "metrics" {
config_json = templatefile("${path.root}/EC2.json.tpl", {
mystring = local.mystring
})
}
For this to work, you would have to change the JSON to be:
"datasource": {
"type": "CloudWatch"
"uid": "${mystring}"
}
The file with JSON data should also be renamed to EC2.json.tpl.
[1] https://www.terraform.io/language/functions/templatefile

Using variables in gulp-jade locals from other locals

My problem is the following: I'm trying to refactor a website and to replace all strings into some variables so when I change a variable it changes across the whole website. However, here comes the issue:
I have data in multiple Json files and I get it like so with gulp:
var locals = {
// Content
someContent: require('../data/content-path.json'),
someOtherContent: require('../data/other-content-path.json'),
};
gulp.task('jade:pages', function() {
return gulp.src(pages)
.pipe(plumber())
.pipe(jade({
locals: locals
})
.on('error', notify.onError({
title: 'Jade Error',
message: '<%= error.message %>'
})))
.pipe(gulp.dest('dist'));
});
So I can easily access any key from Jade like so #{someContent.key1}.
However, if I want to use some key from my someContent in my someOtherContent it renders it as a string (not parsing a variable).
someContent
{
"key1" : {
"subkey1": "5",
"subkey2": "9"
},
"key2":"<p>Some markup which parsed as html if desirable</p>",
}
someOtherContent
{
"title": "#{someContent.key1.subkey1} some other text"
}
So it works perfectly if I just use it directly in Jade, but it can't parse such a reference if I use it as #{someOtherContent.title}, and it outputs exactly
"#{someContent.key1.subkey1} some other text"
when I want it to output this instead
"5 some other text"
What could I do here to make it work? Any help is really appreciated.
Thank you everyone.

using JSON file to define array values in Node.js

In node.js my program app.js, i am defining array like this
var myList = [["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]];
console.log (myList)
It is giving output but i want an external JSON file to supply the parameter of myList array instead of me defining it hardcore
i have prepared a JSON file named ppm.json and change my code to
var myList = JSON.parse(fs.readFileSync('ppm.json', 'utf8'));
console.log (myList[1])
my ppm.json is this
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}
it giving me output as undefined in console. what is the problem. pls help.
Without more requirements it's hard to give a definitive answer, but one thing you can do:
app.js
var myList = require('./my_list.json');
console.log(myList);
my_list.json
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
You can use require() to load both JSON and JavaScript files.
For example,
myFile.json:
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
app.js:
var myList = require( './myFile.json' );
console.log (myList)
You're accessing your item wrong. You don't have an array you have an object.
Access your heros age like this:
myList['age']
You might also consider changing your file to look like this:
{
"SAHRUKH" : {
"age" : "47.49",
"lastpict" : "HIT"
}
}
In which case you'd get your hero's age like:
myList.SAHRUKH.age;
//Or Equivalently
myList['SAHRUKH']['age']; //The dot notation above is preferred though!
Or this
{ "heros" : [
{
"name" : "SAHRUKH",
"age" : "47.49",
"lastpict" : "HIT"
}
]}
In which case you'd get at age like:
myList.heros[0].age;
If you adjust your ppm.json file to look like:
[{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}]
It should drop in and work directly. If you wanted to include multiple heroes, it would look like:
[
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
},
{
"hero": "SALMAN",
"age": "47.3",
"lastpict": "FLOP"
}
]
Your resulting myList should be an array in the example you provided, with entry 0 being the first hero object (SAHRUKH) and 1 being the second, and so on.

In the Grunt.js docs, there is a "this.filessrc" option, is it possible to do "this.filesDest"?

I created a Grunt plugin for generating "manifests" in YAML or JSON format. For instance, the task can create package.json or component.json from given metadata, or by using the metadata from one of those files to build the other.
The task also includes an option for reading directories of files to generate "collections" out of files with certain file extensions. So, for example, you can create a "component" manifest that lists out the files required by the component:
{
"name": "My Component",
"description": "",
"version": "",
"scripts": {
"jquery.js",
"component.js"
"one.js",
"two.js",
"three.js"
},
"styles": {
"component.css"
}
}
So, both src and dest are used in the task for building the "collections", however, when you are only generating a package.json or component.json for instance, you only need the dest.
I didn't find a native Grunt method for doing this, or another clean way of accomplishing the same goal?
You can use one of:
grunt.file.expand
grunt.task.normalizemultitaskfiles
Example (simplified):
module.exports = function( grunt ) {
"use strict";
var util = require('util');
grunt.initConfig({
pkg: grunt.file.readJSON("package.json")
});
grunt.registerTask('default', ['normalizeMultiTaskFiles', 'expand']);
grunt.registerTask('normalizeMultiTaskFiles', function(pattern) {
var result = grunt.task.normalizeMultiTaskFiles(['./public/**/*']);
console.log(util.inspect(result[0].src));
});
grunt.registerTask('expand', function() {
var result = grunt.file.expand(['./public/**/*']);
console.log(util.inspect(result));
})
};
Output:
Running "normalizeMultiTaskFiles" task
[ './public/css',
'./public/css/main.css',
'./public/index.html',
'./public/js',
'./public/js/file1.js',
'./public/js/file2.js',
'./public/js/file3.js',
'./public/js/index.js',
'./public/js/lib',
'./public/vendor',
'./public/vendor1.js',
'./public/vendor2.js' ]
Running "expand" task
[ './public/css',
'./public/css/main.css',
'./public/index.html',
'./public/js',
'./public/js/file1.js',
'./public/js/file2.js',
'./public/js/file3.js',
'./public/js/index.js',
'./public/js/lib',
'./public/vendor',
'./public/vendor1.js',
'./public/vendor2.js' ]