Handling JSON objects with UUID keys while templating with Handlebars.js? - javascript

I have a nested JSON object which looks like this
review:{
body:{
"1cfd0269-1b8f-418f-a7b2-45eb2fa7562b": "Text1",
"38d14dcd-6e70-46f9-8d81-9c5237cb7393": "Text2",
"01485828-39ef-4929-9e96-19758375eb9b": "Text3",
}
created_at: "2014-06-25T07:42:19Z",
id: "ea07aaa3-9db6-4868-b6f1-0887ef77f8ba",
product_id: "eb5a7c9c-c20d-4539-b04f-5a3fd8d26c87",
updated_at: "2014-06-25T07:42:19Z"
written_by: "09b3c6f1-cbcb-4544-8cc3-d073d17a8552",
written_on: "2014-06-25"
}
The JS is pretty straight-forward:
var context = {review:review};
html = template(context);
The template is largish but relevant part is here
<textarea class="review-body"> {{body["1cfd0269-1b8f-418f-a7b2-45eb2fa7562b"]}} </textarea>
I am getting a Parse error while trying to access attributes of body in an html template. Any ideas why this is happening?
Uncaught Error: Parse error on line 5:
...iew-edit-context">{{body["1cfd0269-1b8f-418f-a7b2-45eb2fa7562b"]}}</tex
-----------------------^
Expecting 'ID', 'DATA', got 'INVALID'

From the doc on Handlebars expressions :
To reference a property that is not a valid identifier, you can use segment-literal notation, [ :
{{#each articles.[10].[#comments]}}
{{/each}}
which means you have to use {{body.[1cfd0269-1b8f-418f-a7b2-45eb2fa7562b]}} in your template.
See http://jsfiddle.net/nikoshr/KVg9P/ for a demo.

yes that is work on webpage and angularJS expression retrieve it fine , but if you try to do the same in JavaScript it will return undefined error . for example if you try something like this
console.log(body.[1cfd0269-1b8f-418f-a7b2-45eb2fa7562b]);
or even
console.log(body['1cfd0269-1b8f-418f-a7b2-45eb2fa7562b']);
I do not the solution for it , but somewhere mention JavaScript is not like those mines sign on UUID , myself still looking for solution but temporary I am trying to remove the mine sign.

Related

Flask jinja2 renders new line from database field with errors in javascript

I am saving data in Flask application from a textarea.
After saving it I am trying to receive it back to html via javascript like this:
const item = "{{item}}";
It gives me the following error:
Uncaught SyntaxError: Invalid or unexpected token
On server side I am just retuning lik this:
item = Item.query.filter_by(id=id).first()
item=item.body
Error appears only when i save via textarea with a new line.
How can I fix this?
So far I tried: this works only if I change from '' and "" to template literals ``:
const item = `{{item}}`;
But I am not sure if this method is safe since it makes auto escaping. From jinja2 documentation: "String literals in templates with automatic escaping are considered unsafe because native Python strings are not safe."
Also const item = "{{item | safe}}"; seems not helping.

Error trying to create a regex for Zapier

SOLVED: The error cause was the way I was declaring output var, please see the code
I am trying to create a regex to get the URL from a VSTS attachment in order to sync it with Jira. I tried to create a Run Javascript block with the following input:
Input Data
comment:
creationDate: 2017-10-11T11:31:19.293Z
lastModifiedDate: 2017-08-29T12:32:51.393Z
location: https://project.visualstudio.com/_apis/wit/attachments/ca6206de-0fab-451a-b0bc-89e70221dfcb
name: Capture.PNG
resourceId: 2255679
What I want to retrieve is the "location", so I thought that this would make the trick:
var regEx = new RegExp('location: (.*)', 'g'); // As mentioned in the comments, the 'g' part is not needed
var path = regEx.exec(inputData);
// output = path[1]; This was failing miserably
var output = [{'path': path[1], 'hello': 'world'}] //This works just fine, I guess the hello world part is not really needed :)
But I always get an error:
TypeError: Cannot read property '0' of null
I have tried to create a simple javascript test to run the same and it works just fine. Can you please help me?

How to get specific data from large json object into Jade mixin

This is the json from my sever:
data = {"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "country":null};
I then pass that through a Jade temple like so: res.render('editUpload', {fromServer:data});
Then in my Jade template I have this:
var data = !{fromServer};
console.log(data.address);
Which correctly prints mississippi
However, I'm trying to get my mixins to use that data
Mixin:
mixin textBoxMixin(name, label, value)
div(style="display:flex; width:100%;")
span.label #{label}
input(type="text", name="#{name}", value="#{value}")
Then I use that like this:
+textBoxMixin("title", "Title", fromServer)
which fills in the text box with the entire json "{"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "country":null}" so I go and try this:
+textBoxMixin("title", "Title", fromServer.title)
it prints "undefined".
How do I get this mixin to accept what should just be fromServer.title?
I've tried JSON.stringify(fromServer), data.address (which obviously doesn't work because data is undefined during the rendering of the page). I know that I could go back to my server and parse out all the json there and pass each item as an individual item, but that would be a giant pain since my json is actually much larger than what I've posted here.
The problem was that I was sending the json from the route.js file to the template after having passed it through JSON.stringify(), this let me use var data = !{fromServer}; in the page's scripts, but Jade couldn't parse the String. So now I'm doing this in the route so that I have both the json available for templating and the String for JavaScript:
data = rows[0][0];
stringFromServer = JSON.stringify(rows[0][0]);
res.render('editUpload', {fromServer:data, stringFromServer:stringFromServer, username: req.session.user});
When you reference parameters in your mixin definition, you pass them exactly as if it were normal pug code, without quotes and braces.
mixin textBoxMixin(name, label, value)
div(style="display:flex; width:100%;")
span.label= label
input(type="text", name=name, value=value)
+textBoxMixin("title", "Title", fromServer.title)
Here's what renders:
Also, Jade is now Pug, and I know you know that since you tagged Pug in this question, you should start referencing it as Pug :).

Underscore.js: TypeError: rc is undefined when using templates

I'm using underscore.js to create templates. I am utilizing the rc variable discussed here and I'm getting rc is undefined messages in my firebug console along with this tidbit:
((__t=( rc.siteid ))==null?'':_.escape(__t))+
I tried sending in empty json as specified like so: var mytemplate = _.template([code], {}) as the issue comment suggested, but the error still persists and my templates don't work.
The solution for me was to always explicitly send in an empty json {} if I didn't have any options to send in. The code would look like this:
var mytemplate = _.template([code]);
$('body').append(mytemplate({}));
I'm creating this question/answer because I did not find a solution on SO or via google.

Display JSON data using handlebars.js

I need to figure out how to print the full JSON response onto my page (or even parts of it), but I can't seem to figure it out. I am going to eventually fill out the page with more context later.
JS file:
app.get('/', function(req, res) {
var context
apiLib.fetch('acct:chars', function(err, result){
if(err) throw err
context = result;
console.log(result);
res.render('/', context);
});
});
Handlebars:
{{#each context.characters}}
{{this.name}}
{{/each}}
JSON Data:
{
"result": {
'1234':{ //this is the character ID
"characters": {
"name": 'Daniel',
"CharacterID": '1234'
etc...
}
}
}
My page prints nothing, but console logs everything. I am using express.js to handle the routing.
If you want to display the stringified JSON, you can use an helper
JS
Handlebars.registerHelper('toJSON', function(obj) {
return JSON.stringify(obj, null, 3);
});
HTML
<pre>{{toJSON result}}</pre>
One problem is the each helper, here: {{#each context.characters}}. What each does is look within the current context for the variable. You've already passed Handlebars the context object when you called res.render('/', context). So now Handlebars is looking within the context object for an attribute called context, and it won't find it. So you should change that line of code to {{#each characters}}.
The same thing applies to where you wrote {{this.name}}. I think that will actually work if you fix the other problem, but the this is unnecessary, because Handlebars looks at this (the current context) automatically. So just {{name}} should be fine there.
Finally, if you're really trying to just display the JSON file as a page of plain text, you don't need to run it through a Handlebars template. You can just use res.json(context). This will return a JSON response. If your server is configured to handle the application/json MIME type, it should render as plain text in the browser.
Since you are iterating over objects in handlebars, it should be done as -
{{#each context.characters}}
{{#each this}}
{{#key}} - {{this}}
{{/each}}
{{/each}}
If you are using it with Node.js and mongoDB this answer is for you;
Let's say you have the following response from your database called data:
{
_id: "5AAAAAAAAAe04fc1a1", //some id idk
BUSINESS: 'FLEX TAPE',
SHOWMAN: 'PHIL SWIFT',
CONTACT: 'PHIL SWIFT',
PHONE: '11111111113',
ETC: 'yes',
}
What you might want to look for to display the fields is to take advantage from client-side rendering. piping the data with the classic JSON.stringify(data) as okData for instance.. then you can just reference it using the {{}} notation.
e:g.
<p id="some-id" style="display: none"> {{okData}} </p>
<script>
let jsonStrLookup = document.getElementById('some-id').innerHTML
let js = JSON.parse(jsonStrLookup)
console.log(js)
</script>
This would work for SIMPLE applications hope it helps out, and if something seems off comment, I always check on here, and will try to help you.

Categories

Resources