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>
Related
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 ...
I am preparing for GMAT and hence preparing a question bank. gmatclub.com has lots of question and I was able to write a python script that got the questions and respective answers. While getting the data,I am retaining the HTML formatting as some questions will have underline and bold portion.
I want to develop a desktop application that should read the HTML data (i will use excel or access db as datasource). However I am not sure how to design GUI that will render the HTML formatted data. Any suggestions, on if I can use excel or access user form to show HTML formatted data. Otherwise, if I have to use browser, can I implement the logic without server side scripting that is can I use Javascript to access database(IE allows use of ActiveXobject, however it wont work on chrome and firefox thats what MS site says). The reason for not using server side scripting is, so that I can share the source code with my non-tech friends and they can use it without installing anything.
I would recommend making a very simple web page, all stored in a single file (no server side). If you can get all the HTML for the questions and answers using your python code, use that same code to also write the Q&A into an HTML file that looks like what I have below (I note with comments where you should be writing the Q&A).
I would recommend hard-coding the rest of the html file (i.e. the parts outside the Q&A section) into your python code so that it can print this entire file in one fell swoop. You can then just open this in your browser of choice:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var json = [
//Use Python to write in your Q&A's here
{
"question":"Do you want to take the GMAT",
"answer":"<b>Yes</b>, I do"
},
{
"question":"What is LLC?",
"answer":"Limited Liability <i>Company</i>"
},
//End Q&A section
];
function reset()
{
$('#next').hide();
$('#showAns').show();
$('#a').hide();
ask();
}
function showAnswer()
{
$('#next').show();
$('#showAns').hide();
$('#a').show();
}
reset();
$('#next').click(function(){reset();});
$('#showAns').click(function(){showAnswer()});
function ask()
{
var randNum = Math.floor(Math.random() * json.length);
$('#q').html(json[randNum].question);
$('#a').html(json[randNum].answer);
}
});
</script>
</head>
<body>
<div id="q"></div>
<div id="a"></div>
<button id="showAns">Show Answer!</button>
<br>
<button id="next">Next Question</button>
</body>
</html>
Notes
1) They'll need internet connection to use this, since I make a call to google's jQuery (so it's technically not one page), but you can just download jQuery and call it locally.
2) It sounds like you'll just be getting the list of questions once, so it might actually be quicker to format them in excel into the JSON format and then paste them in the code.
I try to access and use different pages in NCBI such as
http://www.ncbi.nlm.nih.gov/nuccore/NM_000036
However, when I used perl's LWP::Simple 'get' function, I do not get the same output I get when I save the page manually (with the firefox browser 'save as html' option). What I do get from the 'get' function lacks the data I require.
Am I doing something wrong?
Should I use another tool?
My script is :
use strict;
use warnings;
use LWP::Simple;
my $input_name='GENES.txt';
open (INPUT, $input_name ) || die "unable to open $input_name";
open (OUTPUT,'>', 'Selected_Genes')|| die;
my $line;
while ($line = <INPUT>)
{
chomp $line;
print OUTPUT '>'.$line."\n";
my $URL='http://www.ncbi.nlm.nih.gov/nuccore/'.$line;
#e.g:
#$URL=http://www.ncbi.nlm.nih.gov/nuccore/NM_000036
my $text=gets($URL);
print $text."\n";
$text=~m!\r?\n\r?\s+\/translation="((?:(?:[^"])\r?\n?\r?)*)"!;
print OUTPUT $1."\n";
}
Thanks in advance!
The page at http://www.ncbi.nlm.nih.gov/nuccore/NM_000036 does a lot of JavaScript processing and also loads a bunch of stuff dynamically. LWP::UserAgent does not do that for you as it cannot run JavaScript.
I suggest you take a look at what is happening in your browser, with Firebug or the Chrome Developer Tools. You'll see it does an XHR request to this URL: http://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=289547499&db=nuccore&dopt=genbank&extrafeat=976&fmt_mask=0&retmode=html&withmarkup=on&log$=seqview&maxdownloadsize=1000000
Now I am not sure how these params translate to the NM_000036, but you should be able to figure that out by looking at some of the JS code that is being run on the page, or trying multiple pages ans looking at the URLs of the XHR calls.
Since this is probably a public service, and I'm assuming you are allowed to take that data, you should consider asking if they have a proper API that you can hit instead of screen scraping the stuff off of their website.
Content you're searching is generated by JavaScript. You need to parse your HTML (from the first response) and find ID for the data you want:
<meta name="ncbi_uidlist" content="289547499" />
Next you need to make another request to the URL in the form: http://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=ID_YOU_HAVE
Something like this (untested!):
my $URL='http://www.ncbi.nlm.nih.gov/nuccore/'.$line;
my $html=gets($URL);
my ($id) = $html =~m{name="ncbi_uidlist" \s+ content="([^"]+)"}xi;
if ($id) {
$html=gets( "http://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=" . $id );
$text=~m!\r?\n\r?\s+\/translation="((?:(?:[^"])\r?\n?\r?)*)"!;
print OUTPUT $1."\n";
}
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!
In the spirit of the "Perl Preamble" where a script works properly whether executed by a shell script interpreter or the Perl interpreter...
I have a Perl script which contains an embedded HTML document (as a "heredoc"), i.e.:
#!/usr/bin/perl
... some Perl code ...
my $html = <<'END' ;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
... more HTML ...
</HTML>
END
... Perl code that processes $html ...
I would like to be able to work on the HTML that's inside the Perl script and check it out using a web browser, and only run the script when the HTML is the way I want. To accomplish this, I need the file to be openable both as an HTML file and as a Perl script.
I have tried various tricks with Perl comments and HTML comments but can't get it quite perfect. The file as a whole doesn't have to be "strictly legal" HTML (although the embedded document should be)... just displayable in a browser with no (or minimal) Perl garbage visible.
EDIT: Solved! See my own answer
Read it and weep Mr. #Axeman... I now present to you the empty set:
</dev/fd/0 eval 'exec perl -x -S $0 ${1+"$#"}' #> <!--
#!perl
... some Perl code ...
my $html = << '<!-- END' ; # -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
... more HTML ...
</HTML>
<!-- END
... Perl code that processes $html ...
# -->
This sounds like a path to pain. Consider storing the HTML in a separate file and reading it in within the script.
Maybe this is a job for Markup::Perl:
# don't write this...
print "Content-type: text/html;\n\n";
print "<html>\n<body>\n";
print "<p>\nYour \"lucky number\" is\n";
print "<i>", int rand 10, "</i>\n</p>\n";
print "</body>\n</html>\n";
# write this instead...
use Markup::Perl;
<html><body><p>
Your "lucky number" is
<i><perl> print int rand 10 </perl></i>
</p></body></html>
You could also drop the use Markup::Perl line and run your script like
perl -MMarkup::Perl my_page_with_embedded_perl.html
Then the page should render pretty well.
Sounds to me like you want a templating solution, such as Template::Toolkit or HTML::Template. Embedding HTML in your code or embedding code in your HTML is a recipe for pain.
Have you considered putting Perl inside of HTML?
Like ASP4 does?
It's a lot easier that way - trust me ;-)