EJS JSON Parsing - html

So this is the html I want to have generated dynamically by an array. I am not sure if this is the best method for Ejs in Nodejs, if not I'll be happy to receive your alternative way of doing it! The JSON looks like that:
{'TOP':{
'title':"TOP1",
'SUBTOP':{
'title':"SUBTOP1",
'article':{'title':'Article','link':'#'}
},
'SUBTOP':{
'title':"SUBTOP2",
'article':{'title':'Article','link':'#'},
'SUBSUBTOP':{
'title':"SUBSUBTOP2",
'SUBSUBSUBTOP':{
'title':"SUBSUBSUBTOP2",
'article':{'title':'Article','link':'#'},
'article':{'title':'Article','link':'#'}
},
'article':{'title':'Article','link':'#'},
'article':{'title':'Article','link':'#'}
},
'article':{'title':'Article','link':'#'}
}
}
},
{'TOP':{
'title':"TOP2",
'article':{'title':'Article','link':'#'},
'article':{'title':'Article','link':'#'}
}
}
]`
Unfortunately, I am too incompetent to solve this problem because I don't know how to parse the JSON... This is the code I got so far:
<ul>
<% for(var i in navtree) { %>
<p>
<h2><%= navtree[i]['TOP']['title'] %></h2>
<h2><%= navtree[i]['TOP']['SUBTOP'] %></h2>
</p>
<% } %>
</ul>
May somebody has any advise for me? Thank you!

Why don't you simply parse (using JSON.parse(object)) it server-side, before rendering?

Related

For loops in ejs

I have a array containing some html content like this.
const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']
I need to render this in an ejs file through a get request
request.render('viewArticles',{array : articleArray})
where 'viewArticles' is an ejs file. I have used the middleware to set the view engine as ejs.
This is the code in ejs
<% for(arr in array) {%>
arr
<% } %>
I am not able to render any html. How to solve this?
'<%- %>' this is help to print html code as it is.
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
for refrence please click visit this site EJS
<% array.forEach(function(item) {%>
<%-item%>
<% }) %>
Try this
<% array.forEach(function(item,index){ %>
<%= item %>
<% }) %>
I'm not really sure how to do what you want exactly , but take a look at this:
First, instead of you creating an array of HTML elements, how about you create an array of objects, like so :
const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];
this way you just have to write the HTML once, and I am fairly new to programming but I don't see a scenario where you would get a response in HTML, usually you query a database for data or from a JSON file... and assuming the array is actually getting passed to the .ejs file, lets iterate though it,
<% for(let a of articles){ %>
<p> <%= a.text %> </p>
</br>
<% } %>
If the array is NOT getting passed, check for these in your code :
// If you installed
..."dependencies" : {
"ejs": "x.x.x",
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");
// If you specified the views path
app.set("views", path.join(__dirname, "views"));
// And the views engine
app.set("view engine", "ejs");
// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times

Can't access deeply nested objects and arrays in EJS template

Hello fellow stackers,
I trying to get the following response to my EJS template.
Currently I have a for-loop which iterates all campaigns.
campaigns.facebook.data[i].insights .data
Just tried this, which works fully and the output is being shown below:
<% switch (campaigns.facebook.data[i].status) {
case 'ACTIVE' : %>
<div class="ui grid">
<p><%- JSON.stringify(campaigns.facebook.data[i].insights) %></p>
...
However, while trying to get the .data object I encounter problems
<p><%- JSON.stringify(campaigns.facebook.data[i].insights.data) %></p>
Even while trying JSON.stringify(campaigns.facebook.data[i].insights.data[0]) doesn't give any luck. What is possibly wrong here?
After adding a conditional statement for checking if the desired object exist, we won't encounter the undefined error anymore.
<% if (campaigns.facebook.data[i].insights) { %>
<p><%- JSON.stringify(campaigns.facebook.data[i].insights.data[0]) %></p>
<%console.log(campaigns.facebook.data[i].insights.data[0])%>
% } %>

sending var in html from view backbone

Hi I am learning backbone.js and as a part of a project I want to send a variable from my view.js file in Backbone to the associated template(.html). How should i do it?
Currently I try to do the following but fail:
In View.js:
$( ".result" ).html( displayChoice );
In html template:
<% if(!displayChoice.localeCompare("true")) { %>
<div class="name" id="choices"><%- choices[i].choice %></div>
<% } %>
Please tell me what is wrong in this approach.

How can I ensure that my Backbone forms return data that's formatted the same way as it came in?

In short:
When using Backbone and Underscore templates, what's the best way to ensure that the data in a form is formatted in the exact same way when POSTed to the server as it was when it was initially fetched?
Longer question:
I'm currently using Backbone’s fetch() to retrieve some data from the server as JSON. On success I'm taking that JSON and using the data in an Underscore template like so:
<div class="module-content">
<form>
<div class="customer-primary">
<% if (ParentCompany) { %>
<div class="row">
<div class="label">Parent Company</div>
<div class="value">
<div class="current-value"><%= ParentCompany %></div>
<div class="editable-value"><input name="ParentCompany" value="<%= ParentCompany %>"></div>
</div>
</div>
<% } %>
<% if (Title) { %>
<div class="row">
<div class="label">Title</div>
<div class="value">
<div class="current-value"><%= Title %></div>
<div class="editable-value"><input name="Title" value="<%= Title %>"></div>
</div>
</div>
<% } %>
…
</div>
</form>
</div>
The JSON has a number of children with multiple entries, like this:
{
"UserID":"12345",
"FirstName":"Brandon",
"Ship": {
"Address1":"33 One Two Ave",
"Address2":"#23D",
"Address3":"",
"City":"New York",
"State":"NY",
"Country":"United States",
"Zip":"10023"
},
"Phones": [
{
"Kind":"Tel",
"Number":"512-123-4567"
},
{
"Kind":"Fax",
"Number":"512-123-4567"
}
]
}
How can I ensure that I build the form out in such a way that it returns an object that's formatted in the same way for easy DB updates?
Please let me know if you need more info!
If I understand your question, you're trying to make sure the JSON data structure matches what the server expects when you're sending data. (And coincidentally, that it's in the same structure that you received from the server.)
What you want to do is override the model's toJSON function so your data is serialized as expected. Then, when it gets persisted by Backbone.sync, the proper data structure will be sent to the remote API.
Take a look at these:
Saving Backbone model and collection to JSON string
backbone.js: overwritting toJSON
I think the best you can do is to validate your model. and make the fields that you need to be sent required, if you need all of them ,then validate your entire model.
This plugin is a good option for this task.
https://github.com/fantactuka/backbone-validator

Update HTML tag in the view with Ajax dilemma

I'm new to this and have no idea how it must work.
I have a partial view in a foreach in my view that lists all news comments for that news article.
I have a textarea with a post button where the user can submit further comments on this news article.
The new news article must be appended to the list, without doing a location.reload. I was told do use AJAX, not JSON.
Here's my controller:
[HttpGet]
[NoCache]
public ActionResult SetCommentOnNews(int newsId, string newsComment) ??
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.SetCommentOnNews(newsId, newsComment, currentUser.UserId);
return Json(new { success = true }, JsonRequestBehavior.AllowGet); ??
}
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null) {
foreach (var newsItem in Model.Results.NewsComments) %>
<% { %>
<% Html.RenderPartial("~/Views/Home/SetCommentOnNews.ascx", newsItem); %>
<% } %>
</div>
my partial:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Web.Areas.News.ViewModels.Home.NewsCommentsViewModel>" %> //this also not right
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png"/>
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %>
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="header">
<h3>
Leave a comment
</h3>
</div>
<div>
<textarea id="textareaforreply" rows="3" cols="160"></textarea>
</div>
<div>
Post
</div>
<script type="text/javascript">
function PostNewsComment(newsId) {
$("post-button").click(function () {
var jqxhr = $.getJSON("<%= //Url.Action("SetCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").text(), function (data) {
if (data.success) {
alert($("#textareaforreply").text());
$('#news-comment').append($("#textareaforreply").text());
}
});
}
</script>
The above JS is what I have and must inject HTML in to the list using AJAX?
I have NO idea how to do this. Can some one help please?
Thanks
To inject HTML into a list using AJAX I would use Knockoutjs with templates instead of partial views. Knockout can be used to render the information in the browser. Views are for rendering server side, which does not jibe well with AJAX.
What do you mean when you say, "I was told do use AJAX, not JSON". AJAX uses JSON as a method for serializing the data that is sent over the network. Are you referring to the JQuery methods ajax versus getJSON? getJSON is just a wrapper around the ajax method that configures it specifically to retrieve JSON using the HTTP GET verb. Either will work fine, but ajax does give you more control in configuring the request.