Passing an include file into a Handlebars layout - javascript

I'm using Node.js, Express 4, and the Handlebars templating processor. Some of the page views that I'm rendering with Handlebars have several kBytes of static inline SVG code. Is there a simple clean way to put the SVG code into a separate file to be included in the Handlebars layout template? Ideally this include file would have a .svg extension, but .hbs would be acceptable.

yesterday I was solving the the same problem. And I finished with loading svg file into string and then pass it to the handlebars template.
var svgTemplate = fs.readFileSync('./public/app/build/images/spriteAll.svg', 'utf8');
var express = require('express'),
router = express.Router();
router.get('/', function (req, res) {
res.render('main', {
svgTemplate: svgTemplate
});
});
//where main.hbs contains:
...
<body class="ng-cloak">
<div class="inline-svg">
{{{svgTemplate}}}
</div>
....
</body>

You can make a static assets folder (e.g. /public) in your project, and include it with Express: app.use(express.static('public')); Put your .svg file in there.
Then in your handlebars file simply add the SVG as you would in a normal HTML project, like <img src="your.svg">

You could try out handlebars-partial-file to include a file's contents as a Handlebars partial.

Related

Use nodejs module in external javascript from the public folder

I included a module in my js file. Now i defined a button in a ejs file, which calls a function in an external js file from the public folder. How can i use the module in this function?
I tried to pass the module as a parameter, but i didnĀ“t work. Is this even the right way to use this module in my external file?
the route js file
var express = require("express");
var router = express.Router();
var R = require("r-integration");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("Upload", { title: "Upload", para: R });
});
module.exports = router;
my ejs file with the button which calls the function loadScript()
Here i also tried to pass the paramter para to the const rModule
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<button onClick="loadScript()">Test Skript</button>
</body>
<script>
const rModule = para;
</script>
<script src="/javascripts/rScriptTest.js"></script>
</html>
the external js file from the public folder.
But here it says, that rModule is not defined.
function loadScript() {
let result = rModule.executeRScript("./RScripts/test.r");
console.log(result);
}
You can't pass a function though an EJS template. It won't serialize cleanly.
You need:
A JS script/module that will run on a browser
A URL for that file (usually provided with express.static)
You fail at the first hurdle. The module you are trying to use describes itself thus:
This is the R-integration API which allows you to execute arbitrary R commands or scripts directly from the node JS environment. This integration works on Windows and GNU/Linux based systems and uses system calls to access the R binary.
There is no way that it is going to achieve that without using Node.js-specific APIs that are not available in the browser.
You could write a web service in Node.js and interact with it using Ajax instead.

How can I have my index.htm file include other html files

using node.
Here is how I serve one from my server:
app.get('/', function(req, res) {
res.sendfile('./views/index.html');
});
With in this index.html file I have two files I need served:
head.htm and body.htm.
In PHP I would just use includes. How is this done in Node?
There's many solutions to the situation here... it comes down to personal preference on which tool you gravitate towards.
One such tool that I have used is EJS. You can read all about it here:
https://code.google.com/archive/p/embeddedjavascript/wikis/Templates.wiki
Edit: An example of such would be having a header and footer template, with an index.ejs page that includes them. (Although you can use include these files at any point in the index page that gets rendered).
Index.ejs (ejs is just the extension used, it's the same as html with rendering tags inside of it):
<% include templates/header %>
<h1> Index page!</h1>
<% include templates/footer %>
Header.ejs:
<html>
<head>
</head>
<body>
Footer.ejs:
</body>
</html>
Inside routes configuration:
app.get("/", function(req, res){
res.render("index");
}
There's obviously configuration requirements that you will need to do, I'm also assuming you're using express, which EJS works pretty easily with.
Pick a template library, any template library. I've had success with nunjucks.
Then you can do something like:
var nunjucks = require("nunjunks");
var app = express();
nunjucks.configure('views', {
autoescape: true,
express: app
});
app.get('/', function(req, res) {
res.render('index.html');
});
and in index.html:
{% include "item.html" %}
It would help if you mentioned the templating engine you are using. By default, it should be Pug(or Jade) (if you used the express generator I think).
For Jade:
app.js:
var express = require('express');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// define routes
app.get('/', function(req, res) {
res.render('index.html');
});
Now, by default the views folder will be used to serve files. A good practice is to create a master layout that defines the general structure of your HTML files, and then add the specific contents in the extended files.
master.pug:
doctype html
html
head
title
block title // title block
link(rel='stylesheet', href='/stylesheets/default.css') //some default styles
block styles // block for more styles
body
include header.pug //include header file
block content // block to insert contents
script(type='text/javascript',src='/javascripts/faculty-index.js') // default scripts
block scripts // block to insert scripts
include footer.pug // include footer file
Block defines a space where you can enter your content once you extend the file. Include basically just includes the code from the file in that space. Now you're index.pug can be something like this
index.pug
extends master.pug // extend the base template
block title
| Index Page // adds the content in the title block
block styles
link(rel='stylesheet', href='/stylesheets/index.css') // specific styles for index
block content
h1 This is the index // adds the index content which goes in the body tag where content is defined
Here the index file uses everything from the master file, and adds its own content in title, body and styles.
Look at the pug documentation for more
Similar behavior can be replicated with any templating engine. Another one I've used is Handlebars which I like more because its syntax feels more like writing html. But, you'll have to set it up first.

Send a index.html file when server is created

I want a file like index.html to be loaded when the server is created. When I execute the server.js using node, I send a response as text like this res.end("text"). But I want the index.html to load.
I tried to load it using sendFile() in app.get('/getFile') but when I type in the address bar, I get the text for all the urls..even for localhost:3000/getFile.
This is my server.js:
(function(){
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));
var server = http.createServer(function(request, response) {
response.end("text");
});
server.listen('3000');
console.log("Server is listening");
app.get('/getFile',function(request,response){
// response.end('shi');
response.sendFile(path.join('/index.html'));
})
})();
Change the following in your code:
var server = http.createServer(function(request, response) {
response.end("text");
});
to this:
var server = http.createServer(app);
Now, you can serve your static index.html file with this code:
app.get('/', function(req, res, next){
// Serve the index.html file in the root directory of the website.
res.sendFile(path.join('/index.html'));
});
I hope this helps. If you have any questions, let me know.
EDITED
I just made a folder and wrote the following code and I have checked that this is working.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/indexz.html');
});
app.listen(1339);
console.log('Open this link http://localhost:1337');
Steps
1 Copy the code given above in a new folder and name it whatever you want, name the file server.js
2 go to your cmd and propagate to location of your code and now npm install express
3 now type node server on console
4 open the link that is there on the console.
Note : Make sure there is folder name public and there is a file named
indexz.html in there.
Edited
Regarding proper client side files arrangement
You will have to keep all your files in public folder, first of all and attach them accordingly in your html document.
Example
<!-- Owl Carousel Assets -->
<link href="css/owl.carousel.css" rel="stylesheet">
<link href="css/owl.theme.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="angular.js"></script>
<script src="controller.js"></script>
and then within public folder you'll have folders named js and css and in root of the public folder your html files.
Looks your issue is with all the static assets.
In application server like express you have 3 different kind of elements to serve:
static content: this is all html, client side js, css, images and so on
server side templates or views, are documents you assemble with some sort of templating library like handlebars or jade to produce html
api that provide data in xml or more common json format
Your issue is how to serve a static part.
You should add to the static folder of your express app the folder where you build your angular app.
Not just the index.html you need the client side .js, .css and all images the page require.
UPDATE:
Here you could find the express documentation about static content.
UPDATE:
When you add a static folder to the express middleware, you should be able to access your file directly.
For example, if you have 2 files: $project/static/main.js and $project/static/js/my-lib.js, you should use the following urls:
http://127.0.0.1:3000/main.js
http://127.0.0.1:3000/js/my-lib.js
Considering you're executing the node http server on localhost on port 3000.
If you provide a specific path to access the static content, then you have to rewrite your url so.
If you use a line like:
app.use('/staticFolder', express.static('staticFolder'));
Than the urls to the mentioned files will be:
http://127.0.0.1:3000/staticFolder/main.js
http://127.0.0.1:3000/staticFolder/js/my-lib.js
Also pay attention to the path you provide to express.
You should give a proper path, and it's always safer to use absolute paths:
app.use(express.static(__dirname + 'staticFolder'));
or
app.use('/staticFolder', express.static(__dirname + 'staticFolder'));

How to easily pass a variable with Node.js to the view

I'm trying to learn the basics of Node.js and I can't seem to be able to simply send a variable from app.js to index.html without using Jade or other template engine.
This is my app.js
var express = require("express");
var app = express();
app.get('/', function(req, res){
//I'd like to send this as a variable instead
res.send("some text");
});
app.listen(8080);
This is my index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//I want to alert my variable here please
alert(variableFromAppjs);
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>
Is there a way to do it simply like that?
The reason you can't just "send" the variable from your app.js to index.html is because they're two separate programs. index.html is run ONLY on the client machine through the browser, and app.js is run ONLY on the server.
In order for index.html to receive data from app.js, you'll need to to use XMLHttpRequest to make a request to your Node app.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
You can then receive the data asynchronously and save it to whatever variable you want.
You will need to make sure you're using a server-side templating engine (express comes with jade support).
Use npm to install jade to your express app. and then tell express where the templates are, and, in the get route definition you must instruct express what view to use:
var express = require("express");
var app = express();
// Tell express where your templates are
app.set("views", __dirname + "/views");
// Tell express templates are jade files
app.set("view engine", "jade");
app.get("/", function(req, res) {
res.render("home", {
title: "Home Page",
body: "This is just a test..."
});
});
app.listen(8080);
when all this is setup create views/layout.jade and a views/home.jade
Home.jade will look like this:
extends layout
block content
h1= title
p A tag name followed by the equals (=) sign is like php echo
p= body
ul
li This is a hardcoded list
li With two elements
Layout.jade will look like this:
html
head
meta(charset="utf-8")
title= title
link(rel="stylesheet", href="/css/main.css")
meta(name="viewport", content="width=device-width")
body
block content
div.page-content.text-center
h1 Default content
p anything I put here will be overridden by the home.jade content block Which means that any jade view that doesn't provide a `block content` part will render this text instead.
If you create another route for example:
app.get("/default", function(req, res) {
res.render("test", {title: "Default route", body: "Whatever"});
});
an then its corresponding template views/test.jade
extends layout
p I'm not providing a `block content` so this text won't be rendered
blockquote(class="my-class", id="my-id") In jade, the very first word of a line is the tag to be used by the line, to provide attributes to a tag you use comma-separated HTML attributes in between parenthesis right next to the tag name.
And visit your route at http://localhost:8080/default You will see the default text be rendered.
I hope this is of help.

javascript not loading in HTML file - nodejs + expressjs

I am new to nodejs and expressjs so Im trying to build simple web app to grasp both frameworks.
Here I have built a project with the following architecture:
js
test.js
views
index.html
server.js
my server file looks like this:
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var ejs = require("ejs");
var server = express();
server.use(server.router);
server.use(express(__dirname));
server.set('view engine','html');
server.engine('html', require('ejs').renderFile);
server.get("*", function(request, response){
response.render('index.html');
});
server.listen(port, host);
and my index file like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Starter Template for Bootstrap</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script language="javascript" src="/js/test.js" type="text/javascript"></script>
</head>
<body ng-app>
<div class="container">
<div class="starter-template">
some code
</div>
</div><!-- /.container -->
</body>
</html>
My index.html file loads properly but I cannot get the test.js file to load. How can I fix this?
Use express.static built-in middleware function in Express.
Add this line after server.engine. This mechanism should allow static files to be served e.g. images, javascripts, css
app.use(express.static(__dirname + '/js'));
Now you can load:
http://localhost:1337/js/test.js
change render into sendfile and move your js folder to public folder then add this middleware
server.use(express(__dirname+'/public'));
JS files are rendered as static files.
Ref: https://expressjs.com/en/starter/static-files.html
First create a folder "static" and keep .js files in it.
Now, correct the script tags of these .js files in .ejs file.
in the nodejs side :
var path = require("path");
app.use(express.static(path.join(__dirname + '/js')));//middleware
in the HTML page :
<script src="./my_script.js"></script>
As this files is static, you should add the entire root directory to 'app'.
Like this:
app.use(express.static(path.join(__dirname, '/')));
So that you can quote all of your files by relative path.

Categories