Jan 19th, 2020

Adonis edge JSON.stringify

Adonis.js is an underdog in the Node web framework world. The reason being most node engineers are being asked to move to the AWS Lambda or Google Cloud Functions because they promise better performance that of course, all decision-makers and managers can prove ahem ahem and hence most importantly it's a skill that pays. You are more likely to get hired in the market if you know AWS Lambda vs Adonis.js but I am sure Adonis can be deployed in AWS lambda in more than one way

So you played around with Adonis and liked it and decided to do a simple project using Adonis. then got deeper into it as you liked it more? Happens to all of us.

We came to a point that we wanted to print the value of an object in an edge file. Did you notice {{JSON.stringify(something)}} does not work? It's kinda weird.

{{something.toJson()}} was our next best bet but that didn't work either so at this point, it was time to look this up..

Noticed that top 5 results did not answer the question and anyway writing JSON.stringify is annoying in itself.

If it hasn't bothered you yet you've not been coding long enough :) We know we know there are other ways. Relax!

Anyway back to the point: how to print the object value in edge?

The best way we found was to create a hook. Not created hooks yet? If not then go ahead and create a hooks.js file inside the "start" folder and paste the following piece of code.

const { hooks } = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => { 
 console.log('providers booted'); 
})

Extend the view globals by adding the following to hooks.js

View.global('debugHook', function(obj) {   
  return JSON.stringify(obj);
 })

So your final hooks.js will look like

const { hooks } = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => { 
  console.log('providers booted');
  
  View.global('debugHook', function(obj) { 
    return JSON.stringify(obj); 
  })
})

Now in your edge file you can do

{{debugHook(auth.user)}}

Was the article useful?

Your email address will not be published. Required fields are marked *