sending var in html from view backbone - html

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.

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

href links are not detected in a index.ejs file [duplicate]

This question already has an answer here:
How to escape HTML in node.js EJS view?
(1 answer)
Closed 1 year ago.
I have a nodeJS-HTML application. The html file accepts a form and calls nodeJS function which processes some data and send back some info to the hrml file. I am using views to render the details that need to be posted.
My app.js has this line of code
res.render('index.ejs', { collection: data})
where data is in the JSON format
"Name": "Chegg",
"Description" : "In February 2018, the diet and exercise service ABC suffered a loss.
My index.ejs looks like this
<% for(var i=0; i<collection.length; i++) {%>
<div>
<p align="left"><%= collection[i].Domain %> </p> <br>
<p align="left"><%= collection[i].Description %> </p> <br>
<!-- <td><%= collection[i] %></td> -->
</div>
<% }
%>
Here everything is populated correctly expect the Description. The links are not hyperlinked - but plain text.
Is there a way I can show the hyperlinks?
As mentioned by #dimitristseggenes hyperlinks works with - but not with =
Change
<%= collection[i].Description %>
To
<%- collection[i].Description %>

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])%>
% } %>

EJS JSON Parsing

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?

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.