This is my js code:
task.js
var result = [{user: 'a'}, {'user': b}]
$('#cc_test').html(_.template($('#tpl_vgroup_row_test').html(), result))
template.html
<div id='cc_test'></div>
<script type="text/template" id="tpl_vgroup_row_test">
<%= result %>
</script>
But chrome console shows me this:
Uncaught ReferenceError: result is not defined
What's wrong?
Try passing an object to _.template instead of just a value, like so
var result = [{user: 'a'}, {'user': 'b'}]
$('#cc_test').html(_.template($('#tpl_vgroup_row_test').html(), {result: result}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id='cc_test'></div>
<script type="text/template" id="tpl_vgroup_row_test">
<%= result %>
<%= result[0].user %>
<%= result[1].user %>
</script>
Related
How do I use errorMessage object from routes in a partial.I tried this
Route:-
const express = require("express");
const router = express.Router();
const Character = require("../models/character");
// All Character
router.get("/", (req, res) => {
res.render("characters/index");
});
// New Character
router.get("/new", (req, res) => {
res.render("characters/new", { character: new Character() });
});
// Creat
router.post("/", (req, res) => {
const character = new Character({
name: req.body.name,
});
character.save((err, newCharacter) => {
if (err) {
res.render("characters/new", {
character: character,
errorMessage: "Error Creating",
});
} else {
// res.redirect(`characters/${newCharacter.id}`)
res.redirect("characters");
}
});
});
module.exports = router;
layout:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
</head>
<body>
<%- include("../views/partials/header.ejs") %>
<%- include("../views/partials/errorMessage.ejs") %>
<br />
<%- body %>
<br />
</body>
</html>
partial :-
<%= errorMessage %>
it gives me this error:-
ReferenceError: D:\Web_Development\LGS\layouts\layout.ejs:10
8|
9| <body>
>> 10| <%- include("../views/partials/header.ejs") %> <%-
11| include("../views/partials/errorMessage.ejs") %>
12| <br />
13| <%- body %>
D:\Web_Development\LGS\views\partials\errorMessage.ejs:1
>> 1| <%= errorMessage %>
2|
errorMessage is not defined
Maybe should you try to include specifix variables :
<%- include("../views/partials/errorMessage.ejs", {errorMessage}) %>
Or just check the avaibality of your variable as it's in the main layout...
<% if (errorMessage !== undefined) { %>
<%= errorMessage %>
<% } %>
You are passing data from sever to "characters/new.ejs" this file
and now in new.ejs file you have used layouts such as header and errorMessage by using <%- include() %> statement
and to pass data from new.ejs file to this layouts you need to provide second argument to <%- include() %> statement and object of data that you want to pass
so in your example to pass errorMessage to
"../views/partials/errorMessage.ejs" you need to provide
<%- include("../views/partials/errorMessage.ejs", {errorMessage}) %>
then you can use this passed data to your layout like <%= errorMessage %>
if you want to pass more then one data you can do this
<%- include("../views/partials/errorMessage.ejs", {data1, data2, ...}) %>
try this it might be helpful it worked for me !!!!!
<% if(locals.errorMessage != null) {%>
<%= errorMessage %>
<%}%>
I had the same problem... and I solved it by using this:
<%= locals.errorMessage %>
I'm using ejs to try to output a username from req.user in a node express app, but it doesn't seem to be working.
This is where my username and password come in:
app.get('/', function(req, res) {
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user
});
console.log("req.user:", req.user);
});
At this point, I can see req.user in terminal displayed like this:
req.user: [ { _id: 5890f8a97ef995525d4b78cd,
username: 'dave',
password: 'somepassword',
__v: 0 } ]
This is what I have in index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<head>
<body>
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user.username %>!
Log out
<% } %>
</body>
</html>
And this is the login form:
<!DOCTYPE html>
<html>
<head>
<title>Passport</title>
<head>
<body>
<form action="" method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
</body>
</html>
I initially had this in my index.ejs, but still did not output username.
Hello, <%= user.name %>!
Would appreciate any help.
Based on what your terminal displayed, it looks like req.user is an array containing objects, which means that you would need to access one of the elements in the array before accessing the object's properties.
Therefore <%= user.username %> would be <%= user[0].username %>:
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user[0].username %>!
Log out
<% } %>
Or you could just update the web service to pass in the first element in the user array:
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user[0]
});
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user.username %>!
Log out
<% } %>
You may also want to check if the user array contains any elements to prevent any errors from being thrown if it doesn't:
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: (req.user && req.user.length) ? req.user[0] : {}
});
I have a JSON object representing a hierarchy of digital wallets:
masterWallets = {wallet: {}, childs: [{}, {}, ..., {}]}
the array of childs are other wallets which can contains other wallets... (like a file system).
Here is my html table:
<% masterWallets.forEach(function(masterWallet) { %>
<tr>
<td>masterWallet.wallet.walletName</td>
<td><%= JSON.stringify(masterWallet.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= masterWallet.childs %> ));
</script>
</td>
</tr>
<% }); %>
I would like to pass the array of child wallets (masterWallet.childs) to a function and extract and print some infos. I can see all the childs with:
<%= JSON.stringify(mWallet.childs) %>
But I can't pass this variable to my function. I have in the javascript console:
document.write(window.getChilds( [object Object],[object Object] ));
with this error:
Uncaught SyntaxError: Unexpected identifier
Question: How do I pass a JSON object (or an array of JSON objects ?) to a function ?
If your masterWallets is an object of wallet and childs then;
masterWallets = {wallet: {}, childs: [{wallet:{},childs[{}...{n}]}, ..., {n}]}
<% masterWallets.childs.forEach(function(wallet) { %>
<tr>
<td>masterWallets.wallet.walletName</td>
<td><%= JSON.stringify(wallet.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= wallet.childs %> ));
</script>
</td>
</tr>
<% }); %>
But if your masterWallets is a collection of wallets then;
masterWallets = {{wallet: {}, childs: [{}, {}, ..., {n}]},{wallet: {}, childs: [{}, {}, ..., {n}]}};
<% masterWallets.forEach(function(walletObj) { %>
<tr>
<td>walletObj.walet.walletName</td>
<td><%= JSON.stringify(walletObj.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= walletObj.childs %> ));
</script>
</td>
</tr>
<% }); %>
This is the Html code:
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), :id => 'fav_id_002' %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites "), :id => 'fav_id_001' %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
Below is the Javascript
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
//var value = $(this).val();
console.log(e.target.id);
//console.log(value);
});
//f1();
})
I am unable to get the id or value of the link clicked. How do I get the id of the clicked element? Please help, thanks.
Please see the fiddle example. this might help you
$(document).ready(function(){
$(".test").click(function(){
var clickedId = this.id;
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
asda
asd
asdasd
https://jsfiddle.net/hu7r7hsu/
All you have to do is set a same class for all the anchor tags and after making it common follow the example of below code.
$(".linkClass").on("click", function() {
var clickedId = this.id;
}
Try this code:
$('#fav_id').on('click', 'a', function(){
console.log($(this).attr('id'));
});
This made it work, had to change a little bit in the html.
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite ", :id => 'fav_id_002') %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites ", :id => 'fav_id_001') %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
</div>
Removed the id from the link tag and added it to the img tag.
And the Javascript as below:
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
var imgIdVal = $('img', this).attr('id');
console.log(imgIdVal);
});
})
This gave the output as fav_id_002;
My initial view code:
view/clubs_registration/clubs/test_dropzone_pictures.html.erb
<%= render partial: 'dropzone_pictures', :locals => { :club_id => #club.id } %>
My partial code contains a hidden field:
view/clubs_registration/clubs/_dropzone_pictures.html.erb
<%= hidden_field_tag :club_id, name: :club_id, value: club_id %>
The generated HTML of my partial looks like this:
<input id="club_id" name="club_id" type="hidden" value="{:name=>:club_id, :value=>11500}">
What I really want to do is retrieve the value of club_id from my jquery:
console.log($("#club_id").val()); //-> {:name=>:club_id, :value=>11500}
I just want the value 11500.
How should I do that please?
Try setting the value key to club_id[:value]:
<%= hidden_field_tag :club_id, name: :club_id, value: club_id[:value] %>