Node.js code in html file - html

It is possible to mix HTML with node.js commands?
I want to make my site like in PHP so:
<html>
<!-- Some HTML -->
<?php
echo "example";
?>
</html>
So, server makes all commands, which are included in HTML file and than returns pure HTML to show it in users browser. I need this, because I want to get data from MySQL database and then show it on my site.
In all tutorials I found only:
res.write("<Some html>");
And there is nothing about keeping html in separate files and add to them some server-side js.

Find a templating engine and build your application around that, because what you want is not possible.
For a list of compatible template engines, take a look here:
https://github.com/joyent/node/wiki/modules#wiki-templating

Your example using Express and EJS (which I use). Jade seems like overkill to me, but that's just my opinion.
// index.ejs (the html template)
<html>
<head></head>
<body>
<div><%= example %></div>
</body>
</html>
And in your node app:
app.get('/', function (req, res, next) {
res.render('index.ejs', {
layout: false,
locals: {
example: "Hello world!"
}
});
});
That's pretty much the basics of using EJS. I personally like it over Jade because the people I use to do up the html don't hand it to me in Jade format, and it's very similar to how I used to do php templating.
There is more you can do with the templates of course, you can put javascript in them to say, loop through an array returned by a database, include other .ejs files. You just need to dig into the docs and examples on the web.

Use the function res.write is enough.
You can generate some string with html syntax, like "<html>..</html>", then you put it into the res.write and you get response with a html file.
The point is how to generate the string with html syntax.
If we have a template file like this:
<html>
<body>
<h1>{{ "Hello" + " world!" }}</h1>
</body>
</html>
We want to get the "Hello world!" between <h1> and </h1>. So we can have the work done by:
read the template file with fs.readFile
use regular expression to get the content between {{ and }}
use eval to evaluate the content, and replace them.
After doing this, you can get the string with html syntax. and that is what most template engines(like ejs, jade) do, of course they have more complex works to do.
I hope that this can help you know more about template engine with node.js, and please forgive my poor English...

Have you tried a web application framework like express?
Check it out here!

Related

Am I able to link another HTML file in another html?

I currently have a pageMaster file which is an HTML file. I am trying to keep it clean. I am linking my javascript files to this pageMaster for example <script type="text/javascript" src="/resources/js/mainpage.js"></script>. I would like to link an HTML page this pageMaster to avoid having a clutter. Is this possible?
This is what i'm attempting <script="text/javascript" src="/resources/state-icons.html"></script> but it is not receiving back the icons I am expecting
Since html isn't a script, you can't load it as an script (using <script type="text/javascript"> does't make a lot of sense, does it?).
You have to use a preprocessing language, like php, which will build the output on the server. Using php, you could have something like:
<p>Some html
<?=file_get_contents(__DIR__.'/resources/state-icons.html')?>
...more html...</p>
Or:
<?php
include(__DIR__.'/header.php');
?>
...html...
If you can't or don't want to use a server-side language, you can do this with javascript. You can download the contents of the other page and insert them wherever you want (I will use jQuery just because it's easy to write, you don't actually need it):
HTML:
<span class="some-placeholder-for-state-icons"></span>
JS:
$(function() {
$.get('/resources/state-icons.html',function(html) {
$(".some-placeholder-for-state-icons").html(html);
});
});
Of course, this way will be slower and produce more requests per page view. Which one is better depends on what you want to achieve.
You can't do something like this with html. This is possible only for javascript file or stylesheets (css)

HTML repetitive blocks

I wish to do the following things:
Insert external html blocks into new html pages
Use the same html header from one html file for a number of pages, without recreating the header again for all the pages
Please help!
You can use HTML Imports which is part of Web Components:
<head>
<link rel="import" href="/path/to/your/file.html">
</head>
If your page does not have to be pure HTML, you should consider using PHP or a similar server-side language.
There are plenty of options, depends on you:
1) use iframes (a lot problems with responsibility) http://www.w3schools.com/tags/tag_iframe.asp
2) ajax call in javascript, load external resource and then print it in placeholder tag (example is with jquery) http://www.w3schools.com/jquery/jquery_ajax_load.asp
3) use some server language/preprocessor (php, ruby, nodejs), depend if you can (need to by installed on server)
4) also there are static page generator, you add marks in your html, and they will compile html with marks to full static html http://hyde.github.io/ for example.
What you are talking about appears to be a process called templating. There are many ways to do this, including writing Javascript to insert pre-written HTML templates into the DOM (the webpage). You might also consider using a pre-written templating library such as http://handlebarsjs.com/ or another library which contains templating functions like http://underscorejs.org/. A simple MVC guide like:
http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html
May be helpful too, to get you started.
In a more practical sense, here's one possible solution:
To begin I would recommend putting the 'blocks' you want to insert in a separate folder. In the website I run, for example, I place them in the \templates folder (or subfolders) but you can more or less call it what you want as long as it makes sense to you. For our purposes let's say we've created block.html and put it in our \templates subfolder...
Now, within each template you will have whatever you want to load in; something like this:
<h2>Title of section</h2>
<p>My text.</p>
Or whatever you'd like. Then, you'll probably want to add an element to your main page which calls some Javascript, which loads your HTML template in when a particular condition occurs. For example, if you wanted to load in our block.html file you might write something like this:
<div id="calling-block" onclick="menuClicked('locationToInsert', 'block')"></div>
Which would call a Javascript function called 'menuClicked()' when we click the div with the id 'calling-block'.
Within the function we would write something like this:
<script>
function menuClicked(insertEl, UrlString, onTemplateLoaded) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(insertEl).innerHTML = xhttp.responseText;
if (onTemplateLoaded) onTemplateLoaded();
};
};
console.log(UrlString);
xhttp.open("GET", UrlString, true);
xhttp.send();
};
</script>
This is a very simple way of doing things and I'm sure people will tell you there are problems with it, so I would definitely recommend doing your own reading as well, but I hope this covers the very basics.
You need tu use a server side functionality like php, aspx ...

How to parse a Razor template with partials from a custom folder?

I have two cshtml-files in the same subfolder of Views. One of the templates is meant to include the other template. I tried to accomplish that as follows:
Main template:
<html>
<head></head>
<body>
#Html.Partial("~/Views/Pdfs/Header");
</body>
</html>
The error I get is
Unable to compile template. The name 'Html' does not exist in current context.
What am I supposed to do additionally?
As commented by Erik there is no Html in RazorEngine (see the linked answer), however you can use #Include("mytemplate") instead.
If you want to be compatible with the #Html.Partial() syntax for some reason you can extend the RazorEngine syntax like this.
Basically what you want to do is provide your own class inheriting from TemplateBase<T> (or ITemplate to be exact) and then set it either via configuration or the #Inherit MyBaseClass<MyModel> syntax. In this case you could just call the Include method from your Partial method within the Html helper class.
Been annoyed by this for a long time. Wrote all the infrastructure classes to just get this working like you'd expect in MVC, without all the MVC burden:
var razor = RazorHelper.O;
var html = razor.RenderFromMvc(#"Views\RazorEngine\TestEmail.cshtml", vm);
https://github.com/b9chris/RazorEngineComplete

How can I call a Perl script inside HTML page?

I have a single HTML file, how I use a Perl script(date/hour) in the HTML code?
My goal: show a date/hour in HTML
Obs.: alone both script are ok.
Example:
HTML File:
<html>
<body>
code or foo.pl script
</body>
</html>
Perl script(foo.pl):
#!/usr/local/bin/perl
use CGI qw/:push -nph/;
$| = 1;
print multipart_init(-boundary=>'----here we go!');
for (0 .. 4) {
print multipart_start(-type=>'text/plain'),
"The current time is ",scalar(localtime),"\n";
if ($_ < 4) {
print multipart_end;
} else {
print multipart_final;
}
sleep 1;
}
Perl is a server-side language, so it must be run on the server. The HTML code is displayed in the browser, and it is generated by the server. So you would have to run the perl script on the server to generate the date / hour, and embed that into the HTML code that you serve to the browser.
Here is a tutorial on how to do this.
It sounds like you want Ajax. Your HTML page uses JavaScript to call your Perl program. Your JavaScript gets the response and replaces the part of the page where you want the data to go. Alternatively, you can just skip the Perl bit altogether and just do it all in JavaScript.
You can either generate the entire HTML page via a CGI script (as per Chetan's answer) - or as an alternative you can use one of the templating modules (EmbPerl, Mason, HTML::Template, or many others).
The templating solution is better for real software development, where separation of HTML and the Perl logic is more important. E.g. for EmbPerl, your code would look like:
<html>
<body>
[- my $date_hour= my_sub_printing_date_and_hour(); # Logic to generate -]
[+ $date_hour # print into HTML - could be combined with last statement +]
</body>
</html>

Common Header / Footer with static HTML

Is there a decent way with static HTML/XHTML to create common header/footer files to be displayed on each page of a site? I know you can obviously do this with PHP or server side directives, but is there any way of doing this with absolutely no dependencies on the server stitching everything together for you?
Edit: All very good answers and was what I expected. HTML is static, period. No real way to change that without something running server side or client side. I've found that Server Side Includes seem to be my best option as they are very simple and don't require scripting.
There are three ways to do what you want
Server Script
This includes something like php, asp, jsp.... But you said no to that
Server Side Includes
Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.
Client Side Include
This solutions has you calling back to the server after page has already been loaded on the client.
JQuery load() function can use for including common header and footer. Code should be like
<script>
$("#header").load("header.html");
$("#footer").load("footer.html");
</script>
You can find demo here
Since HTML does not have an "include" directive, I can think only of three workarounds
Frames
Javascript
CSS
A little comment on each of the methods.
Frames can be either standard frames or iFrames. Either way, you will have to specify a fixed height for them, so this might not be the solution you are looking for.
Javascript is a pretty broad subject and there probably exist many ways how one might use it to achieve the desired effect. Off the top of my head however I can think of two ways:
Full-blown AJAX request, which requests the header/footer and then places them in the right place of the page;
<script type="text/javascript" src="header.js"> which has something like this in it: document.write('My header goes here');
Doing it via CSS would be really an abuse. CSS has the content property which allows you to insert some HTML content, although it's not really intended to be used like this. Also I'm not sure about browser support for this construct.
The simplest way to do that is using plain HTML.
You can use one of these ways:
<embed type="text/html" src="header.html">
or:
<object name="foo" type="text/html" data="header.html"></object>
You can do it with javascript, and I don't think it needs to be that fancy.
If you have a header.js file and a footer.js.
Then the contents of header.js could be something like
document.write("<div class='header'>header content</div> etc...")
Remember to escape any nested quote characters in the string you are writing.
You could then call that from your static templates with
<script type="text/javascript" src="header.js"></script>
and similarly for the footer.js.
Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.
you can do this easily using jquery. no need of php for such a simple task.
just include this once in your webpage.
$(function(){
$("[data-load]").each(function(){
$(this).load($(this).data("load"), function(){
});
});
})
now use data-load on any element to call its contents from external html file
you just have to add line to your html code where you want the content to be placed.
example
<nav data-load="sidepanel.html"></nav>
<nav data-load="footer.html"></nav>
The best solution is using a static site generator which has templating/includes support. I use Hammer for Mac, it is great. There's also Guard, a ruby gem that monitors file changes, compile sass, concatenate any files and probably does includes.
The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.
HTML frames, but it is not an ideal solution. You would essentially be accessing 3 separate HTML pages at once.
Your other option is to use AJAX I think.
You could use a task runner such as gulp or grunt.
There is an NPM gulp package that does file including on the fly and compiles the result into an output HTML file. You can even pass values through to your partials.
https://www.npmjs.com/package/gulp-file-include
<!DOCTYPE html>
<html>
<body>
##include('./header.html')
##include('./main.html')
</body>
</html>
an example of a gulp task:
var fileinclude = require('gulp-file-include'),
gulp = require('gulp');
gulp.task('html', function() {
return gulp.src(['./src/html/views/*.html'])
.pipe(fileInclude({
prefix: '##',
basepath: 'src/html'
}))
.pipe(gulp.dest('./build'));
});
You can try loading them via the client-side, like this:
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
</head>
<body>
<div id="headerID"> <!-- your header --> </div>
<div id="pageID"> <!-- your header --> </div>
<div id="footerID"> <!-- your header --> </div>
<script>
$("#headerID").load("header.html");
$("#pageID").load("page.html");
$("#footerID").load("footer.html");
</script>
</body>
</html>
NOTE: the content will load from top to bottom and replace the content of the container you load it into.
No. Static HTML files don't change. You could potentially do this with some fancy Javascript AJAXy solution but that would be bad.
Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed or m4 and sending the result over to your server, no, you'd need at least SSI.
The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.