Jade loading a JSON file and assigning to variable - node.js

I have a JSON file in the same folder as the jade template.
Is there a way I can load the contents of the JSON file and assign it to a variable? (FYI - I am trying to do this outside of node.js passing render parameters, I am trying to get this accomplished within jade file itself)
I tried the code below and it does not work. Any pointers?
script.
var jsonValue = include ./demo_options.json

Within the jade, you can not load data, you can load in your node.js app;
var data = require('/path/to/your/demo_options.json');
//
res.render('page', {data: data});
And in your script you can use as follow:
.script
var jsonValue = #{ data }; //this part not sure if it will work

Related

How can get a normal array without quote after being placed in html dataset

I am using express js on my server and ejs as a template engine.
After getting array from my database, I send it to ejs, I then store the data in a dataset in the ejs, while trying to get the dataset using vanilla javascript, I realized that the dataset has stringify my array... How can I get it back as an array?
//ejs
<div class="news_grid" data-kkk="<%=newsData%>">
let a = document.querySelector(".news_grid").dataset.kkk
Make sure the template variable is a properly formatted JSON string, eg, when rendering:
newsData: JSON.stringify(newsData)
Then, in your frontend JS, parse the dataset into an object first:
const newsData = JSON.parse(document.querySelector(".news_grid").dataset.kkk);
// do stuff with newsData.a

Access Node Environment Variables in Jade file

I am trying to figure out how to optionally display text in a jade file based on the environment. I can't seem to figure out how to access the NODE_ENV variable in my jade file.
In my index.jade file I am doing:
if process.env.NODE_ENV === 'development'
h1 I am in development mode
else
h1 I am not in development mode
The problem is that process.env.NODE_env is undefined.
When I try and do: h1 #{process.env} outside of the if statement, Jade outputs [Object Object] onto the page.
When I try and do: h1 #{process.env.NODE_ENV} outside of the if statement, Jade does not output anything onto the page.
I am not rendering my Jade files on fly, rather I am building them all as "static" files whenever I start the server.
Anything you want to access in the jade template has to be in the locals object sent down from the server. For something like the process environment, you can do this right when you fire up your app:
const express = require('express');
var app = express();
app.locals.env = process.env; // though you might prefer to clone this instead of setting them equal
Then in your jade template you can do
#{env.NODE_ENV}
UPDATE
Adding for direct use, rather than in an express server.
const pug = require('pug');
// Compile the source code
const compiledFunction = pug.compileFile('template.pug');
// Render a set of data
console.log(compiledFunction(process.env));
That'll log it, but of course you could just as easily write that to an HTML file using fs utilities instead.

Assign jade variable to Angular

In my application, I'm using NodeJS, Express in the backend and Angular in the frontend. I'm also using Jade template engine.
jade obtains a variable called "adv" by this code.
res.render('page',{adv:result[0]})
In controller.js (for angular)
$scope.content = [];
I would like to do something like
form(ng-init="content=#{adv}")
h5 {{"content" + content}}
i.e. assign that jade variable to the scope. It is not working. I could use http.get and get the content directly to angular scope, but just wondering if it is possible to do this
Thanks
This worked.
- var str_adv = JSON.stringify(adv)
form(ng-init="content = #{str_adv}")
or even (where getContent is a function defined in controller doing the same thing)
form(ng-init="getContent(#{str_adv})")
Both these also parsed the string and stored the object in 'content'
But directly using
form(ng-init="content = JSON.stringify(#{adv})")
gives the same error
It seems assigning objects in ng-init is not possible.
Thanks #ivarni for the hint about stringify

How to pass very large argument to a nodeJS/phantomJS app from the command line

I have a node app running in the background that needs to pass an HTML string too a PhantomJS app to create a render of it. That work fine but in some case the HTML is too long and i get a : Argument List too Long error message.
Here is the NodeJS code i use to spawn the phatomJS process:
var phantom = spawn('./phantom/phantomjs', ['./renderer.js', html, { detached: false });
Also since it's spawning a different process every time, it's very possible that many pages are rendering in parallel.
Any ideas on how this could be overcome ?
I'm going to guess that you are spawning Phantom from node. Instead of passing actual HTML markup to command line, save it to temporary file and pass path to that file. (You can use some packages that provide temp file api to node.)
From there you can just page.open() that path with url like file://<path-from-arg-list>:
// renderer.js
var page = require('webpage').create();
var url = 'file://' + require('system').args[1];
page.open(url, function () {
// …
});

Compile Jade to JSON?

Odd idea, but looking for the simplest approach to define some data files in Jade, and then directly convert them to JSON.
I looked at extending Jade to support a custom doctype, but quickly got lost in the code. For example:
doctype json
Only manual hacky approach I could come up with is convert the Jade to an XML file with jade, and then using better-require to read the XML file in node as an object, and then JSON.stringify the object (yikes)
If you want to use data/JSON in jade, instead of defining some data inside jade, you can pass json directly into response via response.locals or when returning response.render(view, [locals], callback) from node.
In your app.js
res.local.data=JSON.stringify(dataobj);
//or pass variable when rendering
res.render('/index', {
data : JSON.stringify(dataobj)
});
In your jade
function yourfunc(){
var data = !{dataobj};
}
This is dynamic, you can control the variables you are sending into the file, unlike statically defining them in jade.

Resources