Import code from extarnal file to HTML - html

Say I have a text file (test.txt) that contains only the following line:
<h1>Text text text text text</h1>
Is there any command that I can call the contents from this text file in an HTML document, so the contents in the text file imports where the call is made, every time the side shows?
Example: ?????"/test.txt"?????

I believe you mean to ask whether there exists a "command" in HTML which allows you to include a file.
In pure HTML by itself there does not, but the Apache server-side includes does provide such a directive:
<!--#include virtual="./test.txt" -->
You will need to enable SSI processing by your webserver. In Apache, you'd typically call your file .shtml or something like that.

What you're looking for is the concept call "Server Side Includes". Different servers will do this different ways, so you'll need to look at what your server provides.

Not with pure HTML, but you can with PHP (and almost every other server side language):
<?php include("test.txt"); ?>
Or you can do it in a roundabout way with JavaScript if the file is part of the website, you're actually running a web server, and you're not worrying about older browsers:
<script type="text/javascript">
var ajaxRq = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
ajaxRq.open("GET", "test.txt", false);
ajaxRq.send(null);
document.write(ajaxRq.responseText);
</script>

Related

Is there a way to fetch files inside a matlab uihtml component?

I am using a uihtml component inside a uifigure that loads a HTML file in its HTMLSource property. The HTML file just tries to fetch the contents of a text file located in the same folder, and outputs them inside a div component. The body in the HTML looks something like this:
<body>
<div id="viewer"></div>
<script>
fetch("./example.txt")
.then(response => response.text)
.then(textString => {
document.getElementById('viewer').innerHTML = textString;
});
</script>
</body>
The problem is that I always get a "Page Not Found" (the status from the fetch response is 404). The documentation of uihtml says: Common web file types, like JavaScript and CSS, can be referenced from the HTML file you specify for the HTMLSource property, but other web file types might not be supported., so I am not sure if it is even possible to fetch a text/pdf/any other file.
From what I understand, when calling uihtml MATLAB injects an iframe on the webpage displayed by the uifigure. This iframe runs on a local web server, and whenever you append a script tag with a source, the script is also accessed from the web server. For example,
<body>
<div id="viewer"></div>
<script id="script-id" src = "./example.js"></script>
<script>
document.getElementById("viewer").innerHTML = document.getElementById("script-id").src;
</script>
</body>
would display the source of the js file, which corresponds to something like:
https://localhost:31515/static/xxxxxxxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/example.js
That same location of the file we could get by appending the undocumented
connector.getBaseUrl
matlab.ui.internal.URLUtils.parseURL('/example.js',0)
I have tried fetching the text file with the full path to that web server location
(https://localhost:31515/static/.../example.txt)
but the 404 error persists.
At this level of HTML/JS is where I start to struggle. It looks like there should be some way to fetch the data of the file since scripts can be loaded, but I can't find a way. Does anybody know how to successfully fetch the file? Do we need a special credential in the fetch request or something like that?

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 ...

dynamically rendering plain .html page on webmatrix

I'm trying to render a .html webpage using #Renderpage() method in Webmatrix but the .html extension is not supported by the method. I guess the method only supports cshtml extensions. Is there a way I can render html pages dynamically on my site (Webmatrix). I dont want to use an iframe because I'll definitely have issues with my jquery files.
I attempted something i feel is safe yet feels unsafe. I resolved to read the html file and inject it to the DOM manually using:
Array html = null;
var mypage = Server.MapPath(page);
if(File.Exists(mypage)){
html = File.ReadAllLines(mypage);
}
After reading the file.....i injected it to the DOM
<div class="s_content s fontfix left s_content2 downdown">
#foreach (var data in html) {
<text>#Html.Raw(data)</text>
}
</div>
All this runs on compilation time before the page is created for rendering.....I attempted some security measures by attempting to inject server-side C# code in the HTML file but was useless. Makes me feel safe atleast. Is this risky? What is the possible threat to this alternative. i wish i can still have an alternative proper solution from the house. Thanks though.
Assuming #Renderpage() doesn't support HTML files, why don't you try Jquery.load or Ajax. There are lots of tutorials based on dynamic loading of html content.
I do something similar but I don't use #Renderpage or an html file. Instead I am using the "onclick" event and a javascript function which opens a cshtml file. You just put this and the java script function in your main cshtml file in the hmtl section. It will open a file in the current directory called my_window.cshtml when clicked
<a onclick=openWin("my_window",700,850);>Open when clicked</a>
<script type="text/javascript">
function openWin(url, width, height)
{
myWindow=window.open(url,'_blank','width='+width+',height='+height);
myWindow.focus();
}
Hope this helps!

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.