Create pages with pre-compiling the templates - javascript

In my current project, my work is only with html and css (HTML skinning). There are many pages which have repeated sections like Header, footer, sharing links etc.
I don't want to repeat this common sections again and again in each page. I want these repeated sections to call somehow using gulp or any other task runner.
Something like this for example (using lodash)
Index.html
<!Doctype html>
<html>
<%= _.template(templates['head'])() %>
<body>
<%= _.template(templates['header'])() %>
<!-- some unique content here -->
<%= _.template(templates['footer'])() %>
</body>
</html>
and then using gulp-template rendering it in each page. I am preferring lodash because I had already worked with it.
As you can see, I am assuming that if somehow I keep the repeating sections in a javascript object (with name templates), I can call it in one line code. And then if I change something in that repeating section, the change will occur in all pages.
To make this possible, first I need to generate the javascript object with that repeating html as string in it.
Can someone please tell me how to do this? or is there any better way to do this?

You can use Jade - node template engine
It gives option to include external jade files, where in it allows you to insert the contents of one jade file into another
index.jade:
doctype html
html
include ./includes/head.jade
body
h1 My Site
p Welcome to my super lame site.
include ./includes/foot.jade
head.jade
//- includes/head.jade
title My Site
script(src='/javascripts/jquery.js')
script(src='/javascripts/app.js')
foot.jade
//- includes/foot.jade
#footer
p Copyright (c) foobar
Compiles to:
index.html
<!doctype html>
<html>
<head>
<title>My Site</title>
<script src='/javascripts/jquery.js'></script>
<script src='/javascripts/app.js'></script>
</head>
<body>
<h1>My Site</h1>
<p>Welcome to my super lame site.</p>
<div id="footer">
<p>Copyright (c) foobar</p>
</div>
</body>
</html>

Explanation:
Whenever I used to search on google for "pre-compiling templates", I was ending up on sites which were combining all the HTML template files to one single js file. But in my case, I was looking for a way to compile the templates completely on system itself with no support of a "all template compiled js file". (So, I was looking for a solution which pre-renders the HTMLs)
Solution:
I found this awesome template engine, Nunjucks, which lets me compile the HTML templates to Independent HTML pages when used with gulp.
Check this one, gulp-nunjucks-render. By using this along with gulp, I am able to include section of .html files into other .html files. Here is the code (assuming you installed nodejs and gulp):
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-render');
gulp.task('default', function () {
nunjucksRender.nunjucks.configure(['templates/'], { watch: false });
return gulp.src('templates/!(_)*.html')
.pipe(nunjucksRender({
css_path: "../assets/css/",
js_path: "../assets/js/",
img_path: "../assets/images/"
}))
.pipe(gulp.dest('html'));
});
gulp.task('watch', function () {
gulp.watch(['templates/*.html'], ['default']);
});
In the above code, I am keeping the HTML templates in templates folder and with the above gulp code, I am generating the new HTMLs in html folder. The above code will not generate the files which are prefixed with _. (something similar to sass)
and later in command prompt:
gulp watch // Watches the files for changes continuously --> OWNING :D
Here is an example:
<!-- // Index.html -->
<!DOCTYPE html>
<html>
{% include "_head.html" %}
<body>
{% include "_content.html" %}
{% include "_footer.html" %}
</body>
</html>
Which renders to:
<!DOCTYPE html>
<html>
<head>
<title>Website title</title>
<link rel="Stylesheet" href="../assets/jcss/main.css" type="text/css"/>
</head>
<body>
<div class="page">
<!-- content here -->
</div>
<div class="footer">
<!-- footer content here -->
</div>
</body>
</html>
Advantages:
No need of server support to compile the templates.
No need to include any pre-compiled js file in index.html.
Whenever we do some change in common section, no need to include that section again in every page.
Disadvantages:
Till now, I didn't find any :).

Related

How to remove div with id="app" in vue project public/index.html file?

I would like to remove the main div which is in public/index.html file.
Now when I build a project it looks like this:
<body>
<div id="app">
//my code is displayed here
</div>
</body>
But I need to remove div with app id so it should look like this:
<body>
//my code is displayed here
</body>
How I can achieve this in Vue3?
You could specify body as the mount point:
// main.js
createApp({}).mount('body')
If using a Vue CLI scaffold, note this would automatically replace the entire body contents from public/index.html, including the div#app and noscript boilerplate:
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>

Write hyperlink so that an html file loads but internal link to js file changes

This is a general question for which I have searched high and low to no avail, and would greatly appreciate any input.
I have a html/javascript educational quiz that loads a separate js file to retrieve an array to determine the content of the quiz. For example this retrieves the js file with an array of hard level math problems
<script type="text/javascript" src="../js/arrays/math-hard.js"></script>
I have a number of js files with arrays of different content. Another one might load English questions, etc. I need to have a variety of these quizzes, all launched from separate links in different sections of an overall interface.
Currently to create a new quiz I am duplicating the html file and changing the reference to point to the requisite js file for the array.
I would much prefer to have a single html file, and simply write different links that all load that same single html file, but dynamically substitute one of the other js array files to change the content. I cannot figure out how to do this, nor have I been able to find a published solution anywhere.
At the moment the html file is written such that it only references one of the js files that have the arrays, but it's fine to include links to all of them in that single file if that's necessary as part of achieving this functionality.
Currently I have a single html file (stripped down)
<!doctype html>
<html>
<head>
<script type="text/javascript" src="../js/quiz.js"></script>
<script type="text/javascript" src="../js/gridquiz/s-english-easy.js"></script>
</head>
<body>
<div id="gridQuizContent" class="quiz-content">
<div id="divClick" class="quiz-click"></div>
</div>
</div>
</body>
</html>
and it load that english-easy.js, that looks basically like this (simplified)
Quiz.easy = [
['hi-IN', 'dog', 'cat', 'pig', 'cow'],
['hi-IN', 'me', 'you', 'he', 'she'],
['hi-IN', 'up', 'down', 'in', 'out'],
['hi-IN', 'hot', 'cold', 'big', 'small'],
];
And I want to write many links that simply load the same html file but change this line
<script type="text/javascript" src="../js/gridquiz/s-english-easy.js"></script>
as it loads to reference a different array.
If each quiz URL looks similar to the following:
https://quiz.com/quiz.html?quiz=math-hard
https://quiz.com/quiz.html?quiz=math-easy
https://quiz.com/quiz.html?quiz=history-hard
Then you could possibly dynamically load the desired JavaScript file in a 'base' JavaScript file for quizzes by checking the URL path:
// base.js
function dynamicallyLoadScript(url) {
// create a script DOM node
var script = document.createElement("script");
// set its src to the provided URL
script.src = url;
/* add it to the end of the head section of the page (could change 'head'
to 'body' to add it to the end of the body section instead) */
document.head.appendChild(script);
}
let params = new URLSearchParams(location.search);
if (params.has('quiz')) {
dynamicallyLoadScript(params.get('quiz') + ".js");
}
So the HTML of https://quiz.com/quiz?quiz=math-hard would be similar to:
<!doctype html>
<html>
<head>
<script src="../js/base.js"></script>
<!-- Added by 'base.js' -->
<script src="../js/arrays/math-hard.js"></script>
</head>
<body>
</body>
</html>
Personally I would use JSON files to realize this. I found a tutorial on this website, which follows the same problem "how to store quiz questions".

Is there a nice way to route using EJS teamplate avoiding repetition with Express server?

Let's say that my app has two view: index.ejs, profile/index.ejs
I want to route using express code like below.
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index');
});
/* GET profile page. */
router.get('/profile', function (req, res, next) {
res.render('profile/index');
});
should both two ejs files have bootstrap link?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
If the answer is yes, whenever I want to render another page, should I reload style and js file from CDN?
I mean, is there a nice way to keep common contents when I change my EJS template?
There are several ways to achieve this.
1). use partials and include them in every page.
2). If you don't like including the partials in each page then you can use express-ejs-layouts or ejs-locals
For the first approach we can have a partials directory that will contain all the partials we need.
And here are our partials
//partials/head.ejs
<meta charset="UTF-8">
<title>EJS Template</title>
<link ref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
This scipt.js can include all the scripts that you want to include.
//partials/script.js
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
Let's say we want to include these partials in index.ejs then all we need to do is to simply use <% include partial %> and we are good to go.
// index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head %>
</head>
<body class="container">
<header>
<% include partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
<footer>
<% include partials/footer %>
</footer>
<% include partials/script %>
</body>
</html>
Hope this helps !!
No. You can do this easily by adding scripts and css that are used for whole application into different EJS file.
For example.
Create file called header.ejs and add in it all links and scripts.
Then in your templates just include this file, with this piece of code
<head>
<% include header.ejs %>
//IN HERE you can add page specific scripts or links
</head>
Hope this helps

Inclusion of Angular into HTML is being tricky

I am trying to extend my knowledge of JS by learning angular or at the very least get an understanding of angular. I am trying to go through this tutorial but I can not get my downloaded version of angular to load.
I have tried replacing my copy of of the js file with the one included on the GitHub for the tutorial and that works but when I try and link to my local copy it breaks.
This code doesn't work but as soon as the angular file is replaced with one from the repo it works. The two copies of angular are in the same lib folder and I have double checked the names. I have also tried using Google's CDN but that doesn't work either.
Any thoughts on why angular would be acting up this way?
<!doctype html>
<html ng-app>
<head>
<title>Sample AngularJS Controller</title>
</head>
<body>
<div ng-controller="TestCtrl">
<h1>{{title}}</h1>
<input type="text" ng-model="title">
</div>
<script src="lib/jquery-v1.11.1.js"></script>
<script src="lib/angular.js"></script> <!--Fresh Download-->
<!--If I replace the angular.js link with this it works.-->
<!--<script src="lib/angular-v1.2.22.js"></script>-->
<script>
function TestCtrl($scope) {
$scope.title = "Example title! (Change or delete me)";
};
</script>
</body>
</html>

jQuery doesn't work in an external js file

I'm a beginner of jQuery. I wanne write my jQuery in an external js file instead of in the head of html file, but it failed.
index.html:
<!DOCTYPE html>
<head>
<script src="js/func.js"></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
</body>
</html>
func.js
document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>")`
`$(document).ready(function () {
$("#bt_testJQ").click(function () {
$("#response").toggle();
})
})
`
This has nothing to do with putting the code in an external file, you'd have the same problem if it was inline.
document.write's output is placed after the <script></script> element and parsed by the HTML parser when the script has finished running. Effectively, you are:
setting up jQuery to load
Trying to use jQuery
actually loading jQuery
You can't use jQuery before you load it.
The simple solution to this is to use two script elements in the HTML and load jQuery first.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script src="js/func.js"></script><!-- with the document.write line removed -->
just wanna to avoid importing the jquery in every html file.
This is best handled by either:
Using a template system.
Using a build system that combines the contents of all your scripts, including third party libraries, into a single file.
A better way of doing this is have the jquery library called at the head and have your external js script at the last part of the body of your html
html code
<!DOCTYPE html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
<script src="js/func.js"></script>
</body>
</html>

Categories