3

I have a JSON data in dataList variable and I want to add this in custom handlebars helper as a parameter.

var dataList = [
  {
    "id": 1,
    "title": "Arrange meeting",
    "date": "Today 10:35 | By Admin",
    "completed": true
  },
];

Handlebars Custom helper

var Handlebar = require('handlebars');
Handlebar.registerHelper('List', function(data, options){
  //console.log(data) //returns undefined 
  return options.fn(JSON.parse(data)); // gives error
});

Custom Helper Rendering:

{{#List dataList}} 
  {{> widgets/toDoList}}
{{/List}}

It produce error

SyntaxError: Unexpected token u in JSON at position 0

Whereas, it is working with the static data

{{#List '[
  {
    "id": 1,
    "title": "Arrange meeting",
    "date": "Today 10:35 | By Admin",
    "completed": true
  },
]' }} 
  {{> widgets/toDoList}}
{{/List}}
4
  • When I have add full json code in {{#List full_json_code_here}} with single quotes then works perfectly can you please explain it ? or better add the use case in the question, when its working Commented Sep 19, 2018 at 11:49
  • @RaghavGarg Qus. updated. Commented Sep 19, 2018 at 11:54
  • thanks for the update, I am pretty much sure, it's not the problem of custom helper, but the way you are passing data to it. Please also show where you are calling this view.!! If you are using express, it would be like res.render('view-name', data). Commented Sep 19, 2018 at 11:55
  • Thankyou!! @RaghavGarg it works Commented Sep 20, 2018 at 5:49

3 Answers 3

1
+50

I am pretty much sure, it's not the problem of custom helper, but the way you are passing data to it.

If you are using express, it would be like res.render('view-name', data)

Sign up to request clarification or add additional context in comments.

Comments

0

it's becuase your data return undefined see for more here [ uncaught syntaxerror unexpected token U JSON ]

5 Comments

JSON dataList is already defined but still not getting the actual issue.
Handlebar.registerHelper('List', function(data, options){ //console.log(data) //returns undefined return options.fn(JSON.parse(data)); }); in this code you have done parsing into json but due to undefined data you got this error.
Okay!! So can you explain me how to define dataList?? in {{#List dataList }} {{> widgets/toDoList}} {{/List}}
have you ever play with handlebar???? here tutorial for that (video)[youtube.com/watch?v=4HuAnM6b2d8]
@JigneshSanghani , why have you put the question as the answer just reframed? OP told us that the data is undefined and hence the error. Please help in identifying why is it coming undefined..!!
0

JSON.parse accepts a string, but you pass him an array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.