Is there a way to get the HTML of a JADE Template before sending it via response - node.js

What I usually do is:
res.render('myJadeTemplate');
but I want to add another transformation to the html before attaching it to the response.
How can I get the rendered HTML then modify it and send it over via res.send()

If you are using Express3. There is an additional (and optional) parameter to res.render() that is a callback that will give you the rendered HTML rather than sending it directly to the client.
res.render('myJadeTemplate', function (err, html) {
// html => rendered HTML from jade template
});

Ok I found a solution:
var jade = require('jade');
var fs = require('fs');
var jadetemplate = jade.compile(fs.readFileSync('code.jade', 'utf8'));
var html = jadetemplate({
params:"{Some parames}"
});
console.log(html);
Thanks for this thread
Node says Jade has no method "renderFile", why?

Related

Onclick function pug from node

I passed function to render in my pug file. What I want is when the button is clicked, the function should start, but the function starts when I enter the site. Below is how I passed function and using this in PUG file
Router
const start = require('../bot')
exports.home = (req, res) => {
res.render('home', {
functionOne: start.mainFunction()
});
}
PUG File
html
head
link(rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,700")
link(rel="stylesheet" href="/css/main.css")
body
button(type="button" id="mybutton" onclick="functionOne")
The res.render statement is only meant to send data to the template, you can't send a function through there. The Express documentation explains this.
The function is running when you request the page because that's actually what you're telling it to do when you include that function in there.
You will need to write some client-side JavaScript to make an AJAX call or form POST then create a new ExpressJS route on the server to capture that and run the function.

using HTTP.request in ejs render

example in Express I have a route that linked to my ejs middleware.
Code 1 :
app.all("/sample", function(req,res,next){
ejs.renderFile("./sample.ejs", {req,res,next,require,module:require("module")} {}, function(e, dt){
res.send(dt.toString());
});
});
everything fine in the first code. and in sample.ejs (second code) I want to request to some text file in Internet and return to HTML (and should use HTTP module)
Code 2:
<%
var http=require("http");
var url=require("url");
var opt = url.parse("http://website.com/thisfile.txt");
/* it will return "Hello World!" btw */
var dt = ""
var hReq = http.request(opt, function(hRes){
hRes.on("data", function(chunk){
dt+=chunk.toString();
});
});
hReq.end();
%>
<h2>Here is the data is <%= dt %></h2>
and while i try to my browser. it just give me
Code 3:
<h2>Here is the data is </h2>
where I want it gave me
Code 4:
<h2>Here is the data is Hello World!</h2>
How could I get that?
I just want to use HTTP Module or Net Socket Module. and I just want to edit the Code 2. Code 1 is permanently like that.
While EJS can run full JavaScript, you generally want to leave as much as possible out of the template and put more of your logic in your main express request handler.
Since the rendering is done server side anyway, nothing will change other than making it easier to read and test.
You should consider moving the HTTP request made in your EJS template into your app.all('/sample') handler and then just inject the result into your template. In this case that would be the final string collected from the HTTP request. You'll then end up with something like this. (This is untested code).
Also, while it is not required at all, I'd suggest taking a look at something like the request, this makes HTTP requests much easier!
var request = require('request');
app.all("/sample", function(req,res,next){
// Make the HTTP request
request('http://www.website.com/file.txt', function(err, response, body) {
// Render the ejs template
ejs.renderFile("./sample.ejs", {file: body}, function(e, dt) {
// Send the compiled HTML as the response
res.send(dt.toString());
});
});
});

Retrieving HTML from CouchBase into Node.js / Express 4 leaves it unrendered

I'm having a small issue with rendering HTML, stored in CouchBase, fetched by Node.js
In CouchBase I have several small HTML-snippets. They contain text, tags such as <br /> and html entities such as <. They are of course stored as an escaped string in JSON.
So far, so good. However when I pull it out and display on the page, it is rendered "as-is", without being interpreted as HTML.
For example:
[ some content ...]
<p>Lorem is > ipsum<br />And another line</p>
[rest of content ...]
From the controller in Express 4:
var express = require('express');
var router = express.Router();
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://myserver');
var bucket = cluster.openBucket('someBucket', 'somePassword');
var Entities = require('html-entities').XmlEntities;
entities = new Entities();
var utf8 = require('utf8');
/* GET home page. */
router.get('/', function(req, res) {
bucket.get('my:thingie:44', function(err, result) {
if(err) throw err
console.log(result);
var html = utf8.decode(entities.decode(result.value.thingie.html));
// var html = utf8.encode(result.value.thingie.html);
// var html = utf8.decode(result.value.thingie.html);
res.render('index', { title: 'PageTitle', content: html });
});
});
It is then passed to the template (using hogan.js) for rendering.
When looking into this I found that it might have something to do with the encoding of the <'s and <'s that prevent it from being parsed. You can see my converting attempts in the code, where none of the options gave the desired result, i.e. rendering the contents as HTML.
When using utf8.decode(), no difference.
Using utf8.encode(), no difference.
Using entities.decode() it convert < into < as predicted, but it's not rendered even if <div;&gt becomes <div>.
Any ideas?
I found the solution over here: Partials with Node.js + Express + Hogan.js
When putting HTML in a Hogan template, you have to use {{{var}}} instead of {{var}}.
And thus it renders beautifully, as intended :)
Wasn't encoding issues at all ;)

Passing Variable from NodeJS to client-side JS file

Is it possible to pass a server-side JavaScript variable to a <script> tag in an HTML view?
In my routes file I have:
exports.index = function(req, res){
res.sendfile('views/index.html', {
data: {foo: bar}
});
};
If I was using a Jade template, I could do:
script(type='text/javascript').
var local_data =!{JSON.stringify(data)}
To access the data object. However, that doesn't work for an html file. Is there a work-around for this?
Have a route send the data using res.json() and use AJAX in the html to fetch the JSON data.
http://www.w3schools.com/ajax/

How to compile jade template file to get string?

I have a view logic in my jade template file. How can I pass model in to jade and get html for further sending by email ?
You can try the following:
var jade = require('jade'),
fs = require('fs');
fs.readFile('template.jade', 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
var fn = jade.compile(data);
var html = fn({name:'Oleg'});
console.log(html);
});
Where template.jade is the path to your template. And it look like this:
!!!
html
head
title= 'Hello world'
body
p Hello #{name}!
So you pass your model as input of the fn() function, and the output of it will be the html.
<!DOCTYPE html><html><head><title>Hello world</title></head><body><p>Hello Oleg!</p></body></html>
Also you can catch the string from render callback (express example)
exports.test1 = function(req, res){
res.render('test1', { title: 'test1' }, function(err, body) {
console.log(body);
});
res.send('wooo');
};
test1.jade
div
= title
p hello world!
Opening the template with fs.readFile() is no longer necessary. The Jade API includes the compileFile() method that compiles directly from a file.
var jade = require("jade");
var locals = {name: "Linus"},
render = jade.compileFile('template.jade'),
html = render(locals);
The Jade API also includes the renderFile() method that directly returns an html string from a given file, making it even simpler.
var jade = require("jade");
var locals = {name: "Linus"},
html = jade.renderFile('template.jade', locals);
The answers all work for loading the jade template and compiling it to HTML using locals. However if you are sending HTML emails you need to be aware that most clients strip out all CSS classes. Use Juice (or something like it) to apply all of the CSS classes inline.

Resources