I try to load a file with node.js.
In my view, I've got a button :
doctype 5
html(ng-app="lineApp")
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
p filename: #{filename}
button(onclick="location.href='/app/#{filename}'") click me
The page display a paragraph with filename: C:\users\username\my filename.txt.
When I click on the button, the URL is something like http://localhost:8080/app/C:usersusernamemy%20filename.txt
So when I try to retrieve the parameter
exports.appli = function (req, res) {
var filename = req.params.filename;
//....
});
};
with the server side call :
app.get('/app/:filename?', routes.appli);
I got an invalid filename. My question is then, how to pass a file path as a parameter in URL ?
This is a problem with the slashes acting as escape characters.
The first time you pass the string to the client, any escaped slashes (ex: c:\\users\\username\\my file.txt) are converted to single slashes.
When you use href.location, the slashes act as escape characters a second time...which is why they drop out when you try to call the server using it.
You could:
Create two variables to pass to the jade template, one the filename as-is and the other an HTML encoded string
pass the variables to the jade template:
For example, based upon your original jade:
body
p filename: #{filename}
button(onclick="location.href='/app/#{encodedFilename}'") click me
Related
In pug file i have values in "n" i have to pass the values throw the href tag to next page. How to change in href tag. it should be a link not a button.
a(Class=`change_pasword` onclick=`next('${n}')`) Change Password
script.
function next(parmas) {
window.location.href = `/update_password?user_details=${parmas}`
}
How to change the code to href?
You can use just a regular link if you convert the js object to a query string within Pug first.
- const serialize(obj) { ... } // use the formula from the linked answer
a.change_password(href=`/update_password?user_details=${serialize(n)}`) Change Password
Am obtaining the values from nodejs via ajax/fetch and need to pass the same to Pug.
Any help here would be much appreciated
sample.pug
button#searchVal Search
script(type='text/javascript', src='/lib/onClick.js')
br
br
table#table(div='')
each row in slaJobs
tr
th#cbs-tab-header(div='') !{row.jobname}
th#cbs-tab-header(div='') !{row.job_type}
th#cbs-tab-header(div='') !{row.autosys_instance}
dummy.js
.then(function(data) {
console.log(data.jobsHeader)
console.log(data.slaJobs)
})
Need to set value of data.slaJobs from js to slaJobs of Pug
if you can afford to refresh the pug page for the result:
make a request with ajax to some route in node.js.
in the route handler - where you render the pug view - you can pass arguments to your view template.
so when the pug page will be rendered - It will already contain your data.
if you can't afford to refresh:
1. script tag in your template. handle the response and inject the data to the HTML page like any other AJAX
if you are getting data via ajax you should iterate the payload data in a forEach loop and generate HTML into current document. Actually pug is rendered on the server and then the output as HTML will be given to the user.
You can't show your data in your pug view engine while it is already rendered and shown to the user.
a sample:
fetch('localhost:3000/products')
.then(data => data.json())
.then(data => {
var div= document.getElementById('div');
data.forEach(item=>{
var p = document.createElement('p');
p.textContent = item[0] + ' ' + item[1];
div.appendChild(p);
}
})
Trying to send both text and image data as local variables to a server-side rendered page using templates.
I know I have to set the Content-Type as 'image/png'.
How can I set the Content-Type for one variable when all the other variables are text?
Thank you so much!
res.render('profile.html', { locals: {
tasks: tasks,
msgExists: '',
name: req.user.name,
email: req.user.email,
photo: req.user.photo //how to set Content-Type for this variable?
}});
the template is rendered on server side, and then sent to client. this means the content type of the response is "text/html", not "image/png".
your variables do not have "Content-Type", as they are not HTML responses. if you want to embed an image in an html, and you know its raw data, it usually looks like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
now if you have the image data (like whatever after base64 part) somehow stored in a JS variable, and want to pass it to your template renderer to embed that image in the resulting html, it would look like this:
// node js code:
imgData = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
res.render('my.template.html', {
imgData,
// whatever else ...
});
<!-- template code: -->
<img src="data:image/png;base64,{{imgData}}"/>
<!-- whatever else -->
of course this can change a bit based on the exact format you are storing the image data.
I use pug to generate HTML email messages from a template:
doctype html
html
head
title Hello #{name}
body
...
The title is the subject of the email.
Currently, I extract the title text content by parsing the HTML document rendered by pug. But it doesn't seem to be a very efficient way of doing.
Is there some feature or hook available in pug to collect part of the document while rendering it? I considered pug filters, but as far as I understand, those are not suitable since they are triggered at compile time. Not while rendering the document.
I came to a solution using a mixin:
mixin collect(name)
-
// This is just an ugly hack to
// capture the inner block rendered
// text
const savedHtml = pug_html;
pug_html = "";
if (block) block();
const innerHtml = pug_html;
self[name]=innerHtml;
pug_html = savedHtml+innerHtml;
html
head
title
+collect('title')
| Hello #{self.name}
var pug = require("pug");
const compiledFunction = pug.compileFile('template.pug', {debug:true,self:true});
console.log(compiledFunction(out={
name: 'Timothy',
}));
console.log(JSON.stringify(out));
Displaying:
<html><head><title>Hello Timothy</title></head></html>
{"name":"Timothy","title":"Hello Timothy"}
The code of the collect() mixin is not particularly pretty because as far as I know it there is no elegant way to capture the block() output. So I had to tackle into the internal undocumented pug_html variable.
Or is there a cleaner way to achieve that?
Using node.js I am passing some variables to jade view:
res.render('index', {
locals: {
name: user.name,
hashpassword: JSON.stringify(user.hashPass),
languages: JSON.stringify(langs)}
});
In jade file I have:
body
#heading
h1 nodechat
label !{locals.languages} // working - printing whole json string
#content
- var laangs = !{locals.languages} //not working here!
//SyntaxError: Unexpected token .
- each item in laangs
label= item.EnglishName
The problem is that I cannot pass locals.languages to a variable in jade file. If I assign it to a single html element (like label), it's working, but when I try with var = that doesn't work.
What may be the problem?
See my change below...
body
#heading
h1 nodechat
label !{locals.languages} // working - printing whole json string
#content
//- Do it like this...You're already in JavaScript land after the -
- var laangs = locals.languages
- each item in laangs
label= item.EnglishName
Change !{locals.languages} into locals.languages