This is my schema
var productSchema = new mongoose.Schema({
name: String,
description: String
});
var Product = mongoose.model('Product', productSchema);
In my index.js i am using
exports.welcome = function(req,res) {
Product.find({},{},function(err,docs) {
res.render('welcome', {
"productlist" : docs
});
});
};
In my app.js i am calling this statement where routes is my variable to call welcome in index.js
app.get('/welcome',routes.welcome);
My schema is also written in index.js. What i want to do is display all the products with their name and description in my html page named "welcome.html".
Can anyone tell me like what should i write in my html page to do this.
From your latest comment, it means you are using EmbeddedJS as templating engine. Your answer is well documented here.
For complicity, an example of welcome.html to display results is:
<!DOCTYPE html>
<html>
<head>
<title>My Products</title>
</head>
<body>
<ul>
<% for(var i=0; i<productlist.length; i++) {%>
<li><%= productlist[i].name %> : <%= productlist[i].description %></li>
<% } %>
</ul>
</body>
</html>
Related
So in my NodeJS app I wanted to change the canonical link for every page but the problem is that I have made a header component in EJS and used that in every page that is why if I change url from header it is changed site wide.
Well, I have totally forgot I was looking for an answer. I did find a solution.
Method for getting canonical.
const getCanonicalUrl = (req) => {
return ('https://' + req.get('host') + req.originalUrl).replace('www.',
'').toLowerCase();
}
In your route description
router.get(`/${route.path}`, function (req, res) {
const canonicalURL = getCanonicalUrl(req);
.......
res.render(`${route.layout}`, {
canonicalURL,
});
});
And in your meta.ejs template like
<% if (typeof canonicalURL != "undefined") { %>
<link rel="canonical"
href="<%= canonicalURL %>" />
<% } %>
Tell me if it helps!
I'm working on a project in which I have a simple web server hosted with node.js (see code below) and I want to be able to dynamically load the code form html files and modify them each time someone makes a request. I've already putted some marker in my code ${likeThis} and I just need the code to put a string in the right place.
Here is my server code:
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
app.listen(8080);
});
And here is an example page in which I want to change the value ${sampleText} with the plain text "hello world!!!":
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>Titler</title>
</head>
<body>
${sampleText}
</body>
Mind that there might be more of the same or different kind of value all over the html page.
On the user side I'd expect this:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>Titler</title>
</head>
<body>
Hello world!!!
</body>
There are several ways to use live data in pages returned from express. All of them utilize a "template" into which you inject "data". These include:
pug
mustache
handlebars
Another option would be to use NodeJS/ES6 template strings, such as:
const express = require('express')
const app = express()
// Text to insert into template
const sampleText = 'hello world!!!'
// Template to accept sampleText
const result = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Titler</title>
</head>
<body>
${sampleText}
</body>
</html>
`
app.get('/', function (req, res) {
res.send(result);
})
app.listen(8080);
Backticks ("`") are used to define template strings in Node where "${expression}" is used to insert any evaluable JavaScript expression into a template, like:
const result = `The contents of file ${filepath} are: ${fs.readFileSync(filepath).toString()}`
For more information, see Using Template Engines with Express
and for an exhaustive list of template engines that work "out of the box" with Express see Template Engines
i ll illustrate with Mustache, you need webpack for communication between front-side and web-server, but since webpack is headache i ll use mustache CDN.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="message"></div>
//we are gonna render the message into this div tag.
//this is a javascript code
//make sure script tags are at the bottom
<script id="message-template" type="text/html">
<div class="message">
{{message}} . //yes double curly brackets
</div>
</script>
//CDN link, Mustache pack files are stored here and we import from there
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min.js"></script>
//for src add path of index.js in your app
<script src="./index.js"></script>
</body>
</html>
index.js
//select the div that you wanna place the message
const $message = document.querySelector("#messages");
//select the script tag in
const messageTemplate = document.querySelector("#message-template").innerHTML;
const html = Mustache.render(messageTemplate, {
//I hardcoded the message here, but as you learn, you will catch a dynamic data, put it here and display in your html page
message:"hello world",
});
$message.innerHTML(html);
After a bit of work(very flew actualy) i monaged to make this function that allows me to find the strings and replace them with the correct text, i will publish it hoping someone else in the future migth need it:
function substituteString(input, stringToChange, substitute) {
var n = 0;
while (true) {
n = input.indexOf(stringToChange, n);
if (n == -1) { break; } else {
input = input.replace(stringToChange ,substitute);
}
}
return input;
}
Easier than i was thinking
If I have an .html.erb file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<%= #name %>
</body>
</html>
How can I generate an HTML file that looks like this?
<html>
<head>
<title>Test</title>
</head>
<body>
John
</body>
</html>
How can I execute the template (passing the name parameter) given that the format is .html.erb and be able to get just an .html file?
#page.html.erb
<html>
<head>
<title>Test</title>
</head>
<body>
<%= #name %>
</body>
</html>
...
require 'erb'
erb_file = 'page.html.erb'
html_file = File.basename(erb_file, '.erb') #=>"page.html"
erb_str = File.read(erb_file)
#name = "John"
renderer = ERB.new(erb_str)
result = renderer.result()
File.open(html_file, 'w') do |f|
f.write(result)
end
...
$ ruby erb_prog.rb
$ cat page.html
<html>
<head>
<title>Test</title>
</head>
<body>
John
</body>
</html>
Of course, to make things more interesting, you could always change the line #name = "John" to:
print "Enter a name: "
#name = gets.chomp
The ruby ERB library operates on strings, so you would have to read the .erb file into a string, create an ERB object, and then output the result into an html file, passing the current binding to the ERB.result method.
It would look something like
my_html_str = ERB.new(#my_erb_string).result(binding)
where #my_erb_string. You could then write the html string into an html file.
You can read more about binding here and about the ERB library here.
Here is a sample code:
require 'erb'
template = File.read("template.html.erb")
renderer = ERB.new(template)
class Message
attr_accessor :name
def initialize(name)
#name = name
end
def get_binding
binding()
end
end
message = Message.new 'John'
File.open('result.html', 'w') do |f|
f.write renderer.result message.get_binding
end
The template.html.erb is your .html.erb template file and result.html is the rendered html file.
Some nice articles you can take a look, link1, link2.
I've got an angularjs view that I'm trying to print its results and even though the indexing and console output show the data I can't get it to show up in the actual page.
My console output of the json data received:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
$$hashKey: "004"
_id: Object
$oid: "527994c48776385b2e4a6e78"
__proto__: Object
author: "Undefined author"
content: "Undefined content"
title: "stfu"
__proto__: Object
1: Object
$$hashKey: "005"
_id: Object
$oid: "52799b0a8776385c490cd268"
__proto__: Object
author: "adam-stokes"
content: "some content here"
title: "dieeeee"
My controller code:
'use strict';
var cagewebControllers = angular.module('cagewebControllers', []);
cagewebControllers.controller('IndexCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('http://localhost:9000/entity/page').
success(function(data, status, headers, config) {
$scope.pages = data;
console.log($scope.pages);
});
}
]);
My app code:
'use strict';
var cageweb = angular.module('cageweb', [
'ngRoute',
'cagewebControllers'
]);
cageweb.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
» when('/', {
» templateUrl: 'partials/index',
» controller: 'IndexCtrl'
» }).
» otherwise({
» redirectTo: '/'
» });
}]);
my template partial:
<h1>Pages</h1>
{{pages.length}}
<div ng-repeat="page in pages track by $id(page)">
page {{$$hashKey}} - {{page.title}}
</div>
my template layout:
<!DOCTYPE html>
<html ng-app="cageweb">
<head>
<title>{{ title }}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="javascripts/lib/jquery/jquery-1.10.2.min.js"></script>
<script src="javascripts/lib/angular/angular.js"></script>
<script src="javascripts/lib/angular/angular-animate.min.js"></script>
<script src="javascripts/lib/angular/angular-resource.min.js"></script>
<script src="javascripts/lib/angular/angular-route.min.js"></script>
<script src="javascripts/app.js"></script>
<script src="javascripts/controllers.js"></script>
</head>
<body>
<h1>cage-webbbbb</h1>
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
$scope.pages does contain the json data and I can see the data with console.log($scope.pages) but for whatever reason I can not get it to print on the page itself. im not sure if its something easy im missing but a second set of eyes would be much appreciated.
thanks
Thanks to the comments I was able to narrow down my issue. I probably should've mentioned that the application server was nodejs with expressjs using hogan as the templating engine...and guess what, hogan uses the same syntax as angular for processing variables :\ once I switched to ejs I was able to print to the page.
thanks!
Using the new ASP.NET MVC 3.0 Razor View Engine, is there any way to call upon it within javascript code?
In the normal view engine, you could do something like ...
<script type="text/javascript">
$(document).ready(function() {
function somejQueryFunction(obj) {
<%= obj.ExecuteSomething() %>
}
});
</script>
But I cannot find any way to do similar with Razor.
The following should work:
<script type="text/javascript">
$(document).ready(function() {
function somejQueryFunction(obj) {
#obj.ExecuteSomething()
}
});
</script>
Basically any time you have <%: Expression %> or <%= Expression %> you can replace it with #Expression