Is there any example of using a HTML template element within another HTML template element?
okay, here is a simple example:
This is my main file index.html that in it i'm importing the header.html and cloning the template in it and appending it to my master div:
<!DOCTYPE html PUBLIC "_//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xhtml="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<link id="imported-header" rel="import" href="static/components/header.html">
</head>
<body>
<div class="master"></div>
</body>
<script>
var headerImp = document.querySelector('#import-header').import;
var headerTemp = headerImp.querySelector(".header");
var header_01= headerTemp .content.cloneNode(true);
document.querySelector(".master").appendChild(header_01);
</script>
</html>
Then in my header.html I'm importing another HTML and adding it to the template (I got the feeling that calling document is wrong for template in another template, but I could be wrong.):
<link id="import-field" rel="import" href="static/components/credit_field.html">
<template class="header">
<div class="credit"> </div>
</template>
<script>
var creditImp = document.querySelector('#import-field').import;
var creditTemp = creditImp.querySelector(".field");
var credit_01 = creditTemp.content.cloneNode(true);
credit_01.querySelector(".row").innerHTML = "User1";
var credit_02 = creditTemp.content.cloneNode(true);
credit_02.querySelector(".row").innerHTML = "User2";
document.querySelector(".credit").appendChild(credit_01);
document.querySelector(".credit").appendChild(credit_02);
</script>
This is credit_field.html just a template that hold the field:
<template class="field">
<div class="row"></div>
</template>
It is clearly loading it without any error, but it is giving me import error!
just for the record if I import both of them to my index.html and append them in there, it will work just fine, but I'm looking for a way to have a template within another template.
Again to clarify my question, I'm wondering how can I add an HTML template element within another HTML template element?
Note: I have seen people using Django template, but I want to sort it out within HTML, JavaScript and jQuery to avoid complexity.
Easy, you make an ajax call to the html page that you want to be used as template and you place it before or after the proper node
<script type="text/javascript">
$.ajax({
url: 'static/components/credit_field.html',
success: function(content) {
$('template')[0].before(content);
}
});
</script>
Related
I have two html files named homepage.html & dashboard.html at same level under same folder. I only want to fetch a particular div as my main project has a lot of divs.
Here's the code of homepage.html
<html>
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<link rel="stylesheet" href="css/homepage.css">
</head>
<body>
<div class="homepage-side-menu">
<div id="homepage-home">
<label>Home</label>
</div>
<div id="homepage-dashboard">
<label>Dashboard</label>
</div>
</div>
<div id="homepage-main-view"></div>
<script src="js/homepage.js"></script>
</body>
</html>
And here's the code of dashboard.html
<html>
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="css/dashboard.css">
</head>
<body>
<div class="dashboard-side-menu"></div>
<div id="dashboard-main-view"></div>
<script src="js/dashboard.js"></script>
</body>
</html>
I want to only fetch the content from the div class="homepage-side-menu"> and show it under <div class="dashboard-side-menu"></div> using simple JavaScript.
First you have to refer the file which you want to consume. then you use getElementByClass()
here is how you import the html file into another html
<link href="homepage.html" rel="import" />
or using javascript:
<script>
$(function(){
$("#addContentFromAnotherHTML").load("homepage.html");
});
</script>
and you can view something like this:
<body>
<div id="addContentFromAnotherHTML"></div>
</body>
something like this:
var classData = document.getElementsByClassName('homepage-side-menu');
Since html5 you can use imports
<link rel="import" href="/path/to/imports/stuff.html">
In older browsers the only way is using javascript (XHR, fetch, or Jquery .load
Using jQuery you could add this to dashboard.html :
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$( ".dashboard-side-menu" ).load( "homepage.html .homepage-side-menu" );
</script>
There are several ways in which you can share HTML template across several pages
1. jQuery - AJAX load() Method
$(selector).load(URL,data,callback);
The load() method loads data from URL and puts the returned data into the selected element.
Read more about it here
2. Server side inclueds using some server side programming languages
<?
php include 'header.php';
?>
Read more about it here
3. Using some build tools like gulp or grunt or webpack
https://www.npmjs.com/package/file-include-webpack-plugin
https://www.npmjs.com/package/gulp-file-include
4. Using HTML imports
HTML imports is an exciting technology that promises to change how we build websites. Imports allow you to include HTML documents within other HTML documents.
Read more about it here
https://www.html5rocks.com/en/tutorials/webcomponents/imports/
https://blog.teamtreehouse.com/introduction-html-imports
This one is recomended but not works with older browser
This question already has answers here:
Include another HTML file in a HTML file
(41 answers)
Closed 2 years ago.
I have a html "head" template and a navigation template that I want to include in all my other html files for my site.
I found this post:
Include another HTML file in a HTML file
And my question is... what if it's the header that I want to include?
So for example, I have the following file structure:
/var/www/includes/templates/header.html
navigation.html
header.html might look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Test Portal</title>
</head>
In a case like this, can I still follow the example in the other post where they create a div and populate the div via jquery?
Method 1:
I think it would be best way to include an html content/file into another html file using jQuery.
You can simply include the jQuery.js and load the HTML file using $("#DivContent").load("yourFile.html");
For example
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#DivContent").load("another_file.html");
});
</script>
</head>
<body>
<div id="DivContent"></div>
</body>
</html>
Method 2:
There are no such tags available to include the file but there are some third party methods available like this:
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Method 3:
Some people also used server-side-includes (SSI):
<!--#include virtual="a.html" -->
Use <object> tag:
<object data="filename.html"></object>
I needed to include many files. So I created the following script:
<script>
$(function(){
$('[id$="-include"]').each(function (e){
$(this).load("includes\\" + $(this).attr("id").replace("-include", "") + ".html");
});
});
</script>
Use div, for example, to put a placeholder for the insertion.
<div id="example-include"></div>
Created folder "includes" for all files I needed to include. Created file "example.html".
It works with any number of includes. You just have to use the name convention and put all included files in the right folder.
Using HTML <iframe> tag.
I have faced similar problem , then I used
<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>
For anyone interested in a Web Component approach:
<html-include src="my-html.html"></html-include>
And the corresponding JS:
class HTMLInclude extends HTMLElement {
constructor() {
super();
this.innerHTML = "Loading...";
this.loadContent();
}
async loadContent() {
const source = this.getAttribute("src");
if (!source) {
throw new Error("No src attribute given.");
}
const response = await fetch(source);
if (response.status !== 200) {
throw new Error(`Could not load resource: ${source}`);
}
const content = await response.text();
this.innerHTML = content;
}
}
window.customElements.define("html-include", HTMLInclude);
Note that it is possible to do some nice things with a shadow DOM to make sure styling of loaded content does not influence the outer page.
The above code is pretty "modern" JS and you might not want to use the above code directly without some polyfills/babel transpilation.
This is similar to another custom tag solution, but this one uses the text between the opening and closing tags as the include path/url. The other solution uses the src attribute instead.
<html-include> ./partials/toolbar.html </html-include>
The element implementation's a little trickier:
# -- ./js/html-include.js --
class HTMLInclude extends HTMLElement {
constructor(src) {
super();
this.attachShadow({mode: "open"});
if (src) {
this.textContent = src;
}
setTimeout(() => this._load());
}
async _load() {
let src = this.textContent.trim();
if (!src) {
throw new Error("URL missing between <html-import> tags.");
}
let rsp = await fetch(src);
if (rsp.status != 200) {
throw new Error(`Failed to load file (${src}) for <html-import>.`);
}
this.shadowRoot.innerHTML = await rsp.text();
}
}
customElements.define("html-include", HTMLInclude);
The setTimeout() was necessary because this.textContent, if accessed too early, can include all the preceding text of the page (seen on Chrome/Chromium). Deferring the access fixes that.
This is what it looks like incorporated in a page:
<html>
<head>
<link rel="stylesheet" href="./css/index.css">
<script type="text/javascript" src="./js/html-include.js"></script>
</head>
<body>
<html-include> ./partials/toolbar.html </html-include>
<html-include> ./partials/side-menu.html </html-include>
<html-include> ./partials/statusbar.html </html-include>
</body>
</html>
CSS styles should be properly applied to the newly imported HTML.
This element can also be created from JS by passing it the URL to the import file.
let wgthost = document.getElementById("tgt");
wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));
var lPT = document.title.split(' -')[0];
$('.pageBar .left').text(lPT);
With above code snippet, I am trying to display the title of webpage as in below example,
'Home - Sample Website' would come out as 'Home'
The html would be,
<div class="pageBar"><div class="left"></div></div>
I am trying this, but it is not displaying the title. I am relatively new to JS, and I would like to know, what am I doing wrong?
Try using this,
var lPT = document.title.split('-')[0].trim();
$('.pageBar .left').text(lPT);
Also, make use that you are not getting errors in the browser console and you have included the jquery file before this snippet.
Make sure that page title contains - else it will not show anything.
Check below example:
var lPT = document.title.split(' -')[0];
console.log(lPT);
$('.pageBar .left').text(lPT);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Sarjan - My page</title>
<div class="pageBar"><div class="left"></div></div>
Just like T.J.Crowder said:
you need to import jquery
you need to place your code after the you want to manipulate with that code (otherwise when your code runs the DOM element with the .pageBar does not exists yet )
Here is an example:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home - Sample Website</title>
</head>
<body>
<div class="pageBar">
<div class="left">
Sample text
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var lPT = document.title.split(' -')[0];
$('.pageBar .left').text(lPT);
</script>
</body>
</html>
This is a strange one but looks like $dom->saveHTML() is stripping tags from inline javascript
$domStr = '
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>my page</title>
<script>
var elem = "<div>some content</div>";
</script>
</head>
<body>
<div>
MY PAGE
</div>
</body>
</html>
';
$doc = new DOMDocument();
libxml_use_internal_errors(true);//prevents tags in js from throwing errors; see php.net manual
$doc->formatOutput = true;
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = true;
$doc->loadHTML($domStr);
echo $doc->saveHTML();
exit;
http://sandbox.onlinephpfunctions.com/code/ad59a2a1016b2128e437ef61dbe00f1c511bff8d
if you use libxml_use_internal_errors(true); you will not see what is wrong but if removed you get
<b>Warning</b>: DOMDocument::loadHTML(): Unexpected end tag : div
Same thing happens with
$doc->formatOutput = false;
Any help is appreciated.
I've avoided this by not including any HTML in my inline JavaScript. Instead, I've added <template> elements containing the HTML string I want to manipulate in JS, and then I read that dynamically at runtime. For example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>my page</title>
</head>
<body>
<div>
MY PAGE
</div>
<template id="content-template">
<div>some content</div>
</template>
<script>
var elem = document.getElementById('content-template').innerHTML;
...
</script>
</body>
</html>
It is probably a bug of DomDocument.
You have to escape the closing tag of HTML in JS or it gets misinterpreted.
This should work
var elem = "<div>some content<\/div>";
Alternatively, if you pass option 1 to the loadHtml the parser will ignore it.
In a bit of an oddity 1 can mean both LIBXML_SCHEMA_CREATE and LIBXML_ERR_WARNING as these two predefined constants have the same value. Presumably it is meant to be LIBXML_SCHEMA_CREATE which does the following "Create default/fixed value nodes during XSD schema validation".
You're missing the opening <html> tag right after the DOCTYPE declaration.
Can someone help me with stating what am I doing wrong in this example -- http://jsbin.com/bekoxo/2/edit?html,output#H:L23
The screenshot for the chrome inspector is at -
https://www.dropbox.com/s/t6uua7h714h2otg/Screenshot%202014-10-13%2001.32.54.png?dl=0
I can figure out that the element (appler-page) is not registered successfully, template shows document-fragment instead of desired shadow-root
the 2nd element, where polymer definition is part of the markup(same markup) is rendered successfully.
Can someone point out what am I missing in order to make the first part of example also work.
(which is creating an element via javascript and using it immediately)
EDIT --- problem code below
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/platform.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/polymer.js"></script>
<meta name="description" content="problem with dynamically building a polymer element" />
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var scr = '<polymer-element name="appler-page"><template>template content {{test}}</template><script>var proxymodel = {};proxymodel["test"] = "testfie" ;'+
'Polymer(proxymodel);<\/script><\/polymer-element><appler-page><\/appler-page>';
$(document).ready(function(){
document.getElementById("fie").onclick = function(){
var divel = document.createElement("div");
divel.innerHTML = scr;
document.querySelector(".polymerized").innerHTML = "";
document.querySelector(".polymerized").appendChild(divel);
}
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="button" id="fie" value="fie"/>
<div class="polymerized">before content</div>
EDIT -- A better jsbin for the problem
http://jsbin.com/bekoxo/2/edit?html,output#H:L23
Here is one way in which you can register your element imperatively (which, I believe is what your first element is trying to do). I've simplified your example a bit.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import"
href="http://www.polymer-project.org/components/polymer/polymer.html">
<script>
Polymer('appler-page', {test: 'testfile'});
var el = document.createElement('div');
el.innerHTML = '\
<polymer-element name="appler-page">\
<template>template content {{test}}</template>\
</polymer-element>';
document.body.appendChild(el);
</script>
<appler-page></appler-page>
</body>
</html>
See http://jsbin.com/qifupa/edit
Another instance of staying up with the latest Polymer version I found.
here's the working piece of code that may help anyone else if they are attempting the same thing.
I switched to Polymer-project.org addresses for the imports and it worked.
http://jsbin.com/bekoxo/14/edit?html,output#H:L23