Adding CSS File to ejs tempelate using variable from server side - node.js

I am trying to add css file dynamically in ejs tempelate.
I know how to include ejs file but not getting how to add css file dynamically.
Code :-
Index.js
router.get('/', function(req, res, next) {
res.render('template', { title: 'abc',page:'index',cssa:'home'});
});
template.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
<!-- Here I want to add home.css file -->
</head>
<body>
<!-- including my ejs file -->
<%- include(page) %>
</body>
</html>
I tried :
<link rel="stylesheet" type="text/css" href="/stylesheets/\<%= cssa %>\" >
<% include %><%= cssa %><% .css %>
Goal:
to pass the server side received variable(cssa) in stylesheet source.

Don't need to concat the css path and variable, you can also do it as follows:
<link rel='stylesheet' href='/stylesheets/<%= yourVariableName %>.css' />

Method to include :
<% var css_link = '/stylesheets/' + cssa + '.css'; %>
<link rel="stylesheet" type="text/css" href="<%= css_link %>" >
Credit goes to #SpiRT
Alternatively :
<link rel="stylesheet" type="text/css" href="/stylesheets/<%=cssa%>.css">

I've found it most convenient to inject custom css scripts through an array which can then be processed in the ejs template.
This method would allow you to render any amount of CSS files that are additionally required (example, you have a site that uses 1 standard css across all pages but have 1 or 2 page specific ones which can then be included in the model passed through the ejs renderer to that specific page/route).
In the example it's a given that the css files are in the same folder, however that can be changed to each one's liking:
router side:
router.get( ... {
model = {};
model.Stylesheets = [];
model.Stylesheets.push("stylefile");
res.render("view",{model:model});
});
with the custom stylesheets being pushed though to the view, then the ejs files can be something like:
<%
var customStylesheets = "";
model.Stylesheets.forEach(function(style){
customStylesheets+='<link type="text/css" rel="stylesheet" href="css/'+style+'.css">';
})
%>
<!DOCTYPE html>
<html>
<head>
<title><%= model.title %></title>
<link type="text/css" rel="stylesheet" href="css/standard.css">
<%- customStylesheets %>
...
</head>

Related

CSS and JS file not linking in node js

I want to use middleware func to serve static file,but the problem is that my css file is not linking with html file using node and express
error is:
Refused to apply style from 'http://localhost:4000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
app.js:
const express=require('express');
const path=require('path');
const app=express();
app.use('/public',express.static(path.join(__dirname,'static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/static/js/script.js"></script>
</body>
</html>
folder structure is:
static
css
main.css
js
script.js
index.html
app.js
I tried a lot , but i am not able to find the error,
please help!!
Thanks!!
We will have to do something like that:
app.js
const express=require('express');
const path=require('path');
const app=express();
app.use('/public', express.static(path.join(__dirname,'./static')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'static','index.html'));
});
app.listen(3000, () => {
console.log("Starting at", 3000);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/public/js/main.js"></script>
<link rel="stylesheet" href="/public/css/style.css">
</head>
<body>
<div class="asd">
Hi xyz here..
</div>
<script src="/public/js/script.js"></script>
</body>
</html>
Here is the screenshot:
A basic thumbs rule we can think of:
app.use('<something_here>', express.static(path.join(__dirname,'./static')));
<link rel="stylesheet" href="<something_here>/css/style.css">
<link rel="stylesheet" href="<something_here>/css/style.css">
You don't need to add '/' in the path:
<link rel="stylesheet" type="text/css" href="css/style.css">
Also, you should make a change in your app file:
app.use(express.static(__dirname + '/static'));
This way express knows from where it has to serve the static files.
You are serving the static folder at /public endpoint. So you should change the link to
<link rel="stylesheet" type="text/css" href="/public/css/style.css">
and
<script src="/public/js/script.js"></script>
Also check the name of the css file.

EJS/Node/Express - Having a header partial, how to change title for each page?

I recently took a course on back-end web developing.
As the title says, I don't get how can I use a header partial for the whole website but have different titles for each page. (because is included in the tag)
Is there any trick?
1st) In your Express route:
app.get("/", function(req, res){
res.locals.title = "Abel's Home Page"; // THIS LINE IS KEY
res.render("home.ejs");
});
2nd) In your views/home.ejs file:
<% include partials/header.ejs %>
3rd) In your views/partials/header.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= title %></title> <!-- THIS LINE IS KEY -->
<link rel="stylesheet" href="../style.css">
<link rel="shortcut icon" href="../logo_sm.png" type="image/x-icon">
</head>
<body>
Each page that includes the partial is free to pass data to said partial through parameters. See here for an example.

Angular 6 | Express : Getting 404 error on dist files

Thanks for taking the time to read my question. My website works fine when I run ng serve. When I run ng build --prod, that works fine as well. Problem is, when I try to render index.html in dist im getting 404 errors. The errors are 404 errors for my main, styles, and polyfill files. I'm trying to build a back end so that I can process card payments. Any help would be appreciated - have been knocking my head against the wall for hours now with no resolve. This is my code below:
server.js
var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
server.listen(2000, function(){
console.log('Listening on 2000..')
});
console.log(__dirname);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/dist/culture/index.html');
});
src/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Culture</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
dist/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Culture</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="styles.aaf8a2468e47be90b64b.css"></head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.a66f828dca56eeb90e02.js"></script><script type="text/javascript" src="polyfills.b4daf421c94934f530d4.js"></script><script type="text/javascript" src="main.36d7357da7cc32c08c65.js"></script></body>
</html>
Again, in short, localhost is giving 200 code which is good it means its connecting to the right place. The problem is once it is connected it can not find any files. What am I doing wrong? Thanks
You must correct this line of code: app.use(express.static(__dirname)); to something like this: app.use(express.static(path.join(__dirname, 'dist/culture'))); if your Angular app files are in dist/culture directory.
Main problem is that when your index.html for example tries to load <link rel="icon" type="image/x-icon" href="favicon.ico"> it uses request to path http://localhost:2000/favicon.ico. Your express backend have defined static assets on __dirname and your actual app is in dist/culture so your request should look like http://localhost:2000/dist/culture/favicon.ico.
Applied change has improved configuration of static files location.

Files inside the assets folder are not being loaded in sub pages

I have a folder structure like below
assets
bootstrap
css
style.css
js
jquery.min.js
views
partials
head.ejs
header.ejs
scripts.ejs
home.ejs
user_registration.ejs
In my app.js file I have set this assets folder like:
var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');
In my routes.js file
exports.userLogin = function(req, res){
var userLogin = req.params.userId;
var users = memberData.users;
res.render('user_registration', {
title : 'Welcome',
users : users
});
};
In my head.ejs file
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">
Now inside in user_registration file, I have following code
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head.ejs %>
</head>
<body>
<% include partials/scripts.ejs %>
</body>
</html>
By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.
When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css
whereas user_registration page is taking following format
http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css
I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.
Problem is here app.use('/static', express.static('assets')); in your code line.
Replace it with
app.use(express.static(path.join(__dirname, 'assets')));
And in your head.ejs file replace bootstrap css calling line
href="static/bootstrap/css/bootstrap.min.css" to href="/bootstrap/css/bootstrap.min.css"
Hop you understand.
The problem is: the href link to static resource should be absolute, not relative. Specifically, in head.ejs it should be:
href="/static/bootstrap/css/bootstrap.min.css"
...
href="/static/css/style.css"
NOT:
href="static/bootstrap/css/bootstrap.min.css"
...
href="static/css/style.css"
As app.use('/static', express.static('assets')); stated, the static assets are hosted under /static namespace (absolute URL starting with /static), it doesn't make any sense to use relative URL any more.

html-webpack-plugin output html , interior body empty

use html-webpack-plugin output html page , but in output page lost body inner html element , like <div id="app"></div> , here is my input output and webpack.config file :
input
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<link rel="icon" href="static/pic/logo.png" type="image/x-icon">
<link rel="stylesheet" href="static/weui/weui.min.css">
<link rel="stylesheet" href="static/index.css">
<title>APP</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/vendor.js"></script>
<script src="./dist/app.js"></script>
</body>
</html>
output
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SPA</title>
<link href="/dist/style.df241090c6a9e0a6bf26.css" rel="stylesheet"></head>
<body>
<script type="text/javascript" src="/dist/vendor.df241090c6a9e0a6bf26.js"></script><script type="text/javascript" src="/dist/app.df241090c6a9e0a6bf26.js"></script></body>
</html>
part webpack.config.js
const htmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
new htmlWebpackPlugin({
title:'SPA',
filename: 'assets/index.html'
})
],
The filename option is simply used as the output file, it won't read and modify the existing file, if one exists. Because if it did that, every new build would just append to it, unless you cleaned it manually. To use your input as the base, you need to use it as a template.
new htmlWebpackPlugin({
title:'SPA',
filename: 'assets/index.html',
template: 'path/to/template/index.html'
})
The template should not be the same as the output filename, otherwise it gets overwritten. See also Writing Your Own Templates. The template can be a regular HTML file and it will inject the necessary assets.

Resources