I have social buttons for sharing the current page on all my web application pages, the URL attribute is as follows data-url="https://www.myPage.com/whateverComes". However, I am looking for a way to have this URL dynamically from the location.href. Is there a way to achieve this without having to use javascript? maybe just plain HTML or inline javascript.
I am using pug as templating engine, -window.location.href or #{window.location.href} didn't work. Any ideas please ? thanks.
window.location.href is a client side JavarScript variable, pug has no access to it.
Assuming you're using Node.js with express you can do something like this
app.get("/posts/:post", (req, res) => {
res.render("page", {
currentURL: `${req.protocol}://${req.get("host")}${req.originalUrl}`
});
});
then in your pug template interpolate the variable:
a(data-url=currentURL)= Link
Related
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?
static-pages-server.js:
app.get('/index', function(req, res) {
var name = "hello";
res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
});
index.html:
<script type="text/javascript">
console.log(name);
</script>
Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.
<script type="text/javascript">
console.log(<%=name%>);
</script>
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.
Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html
Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.
It would allow you to pass data directly from your routes into the page you are rendering.
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.
Simply modify your index.html like this:
<script type="text/javascript">
let name = "{{name}}";
console.log(name);
</script>
here is the answer How do I use HTML as the view engine in Express?
what you will need is a view engine package in your app. there are many view engines currently available.
then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.
check out esj or pug (ps pug is my personal favourite )
I am looking for an information.
How to pass a variable from NodeJS res.render('index', { title: "Hey"}) to local JS.
I use express (with helmet) and PugJs. I can include my var in the template, but I want to store it on the JS file who's part of the template. (No inline script, vanilla JS)
Currently, I use a hidden Input in the template to store the data, the JS script get the input and do the work.
How I can pass the variable thought the template to my JS file?
Sorry, I 'm French :(
Thank you for your time!
I want to write my HTML in HTML. Not some fancy way. The only thing that would be cool is to be able to use some sort of include statement to include header/navigation/footer for each page.
I've looked at pug, ejs, mustache, nunchuck, etc etc. I hate all of these things. I just want to write HTML..
What is a simple node module to do this? And how do I set up the render engine in my main app.js? I am using express
You can just set up your express routes to connect with html pages. Here's a simple example:
var express = require('express');
// Create express app
var app = express();
// Route index page to an index html page
app.get('/', function(req, res){
res.sendFile(__dirname + '/path/to/views/index.html');
});
// Create server
app.listen(8080, function(){
console.log('Ready on port 8080...');
});
As a side note, ejs is basically html but with some bonus functionality. You can totally get away with writing only html in ejs pages and then start using the ejs features when you get comfortable with it.
Looks like you want to server only static html files using node not some jsp equivalent dynamically generated html.
Express has support for serving static files and you do not need to define any routes for that!
http://expressjs.com/en/starter/static-files.html
Second thing I understood from your post is you want to include some common html to your html page. One way of doing that is to use a browser/client side java script framework. Take a look at angular.js. It has ng-include. Basically you can include one html file to another using that.
I have a client side application written in plain HTML/JS (Not with Angular.js or other front-end MVC framework). It contains multiple html file. each includes different js library.
I would like to provide basic user auth feature(using sails-generate-auth) to limit the access of this client-side application using Sails.js
But I'm having problem putting those html file into /views
Should I change all *.html in to *.ejs and edit /config/routes.js to route each file? How do I make use of the req.session.authenticated ? Please provide some direction. Thank you.
Your solution written in your question would work. Here is another option:
You can send the file straight from your controller or for universal usage you can create a custom response that will send the html file instead of attempting to render the ejs view. Call it sendHtml(), or modify the current ok.js to know and send your html files
http://sailsjs.org/#!/documentation/concepts/Custom-Responses
Use something like
res.sendfile('/views/' + rest.controller + '/' + res.action + '.html');
I've been doing some guide on Mean stack and I came to a point where I'm currently stuck.
Following this guide, I have created a simple authentication where I'm able to log in using Passport JS. Whatsoever, each time when page refreshes, the authentication gets restarted (client doesn't recognise it anymore).
Since this is suppose to happen in the guide and we are about to fix it, guide said the following.
1. Create a Jade file and insert this:
if !!bootstrappedUser
script.
window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}
I've tried this in my html file but it doesn't work:
<script type='text/javascript'>
if (bootstrappedUser != "undefined" ){
window.bootstrappedUserObject = JSON.stringify(bootstrappedUser);
}
</script>
Getting the error: Uncaught ReferenceError: bootstrappedUser is not defined
even though I have created the variable in my backend js file and assigned req.user to it.
I'm suppose to have this file included in my main layout (index.html). The problem is that I'm not using Jade as template engine but plain HTML and I don't know how to transform this code up there to work as simple HTML in my index.html.
It seams that this statement up here only initialise when user hits the login button. Does anyone have any idea or solution how to write the above code in plain HTML.
I browsed StackOverflow and found almost similar problems but not similar enough.
Thanks in advance,
Aleksandar
bootstrappedUser is a variable passed by server-side code to Jade compiler which injects it into the HTML while compiling. If you plan on writing the HTML yourself you can not inject variables from server-side code, obviously because HTML is just a static markup. You'll probably have to get that variable at the client-side from the server yourself via ajax or something.
Via Angular controller let's say ?
You can first define a route on server that serves the variable you want
app.get('/bootstrappedUser', function(req, res){
if(req.user)
res.json(req.user);
else
res.status(401).end();
});
Then on client-side angular you can perform an http request and get that variable
$http.get('/bootstrappedUser')
.success(function(data, status, headers, config) {
$scope.bootstrappedUser = data;
});