Use append to add block of code to different html files

Use append to add block of code to different html files
0

#1

I am wondering if I can use append to add a template literal (a block of code) to different html files. E.g., let’s say I have a couple of html files ( about.html, projects.html, contact.html) and they all share the same <header>...code here...</header> and <footer>...code here..</footer>, instead of manually adding these block of codes in each one of the html files, can I do this with JS somehow ?


#2

Without more details, I can only say, yes you can.
Check out mozilla for developers for more details.


#3

I edited my post, basically I have a block of code in the header and footer section that I would like to add to different html files, and I was wondering if I can do this with JS instead of manually adding these block of codes in each of the html files.


#4

yes, you can do that with vanilla js or you can use some library, like ejs … it is perfect for what you are trying to do…
http://ejs.co/


#5

You can create separate files like header.html and footer.html which would contain applicable content. Then you would in each page where you want to load the contents of these files, you could create a div for each section like:

<div id="header"></div>
.
.
.
.
<div id="footer"></div>

Then you would need to put the following in each page or create a function which gets called which contains these load statements.

$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 

You can only use this code if the files are serve by a webserver and not just your local pc, because you will received a cross-origin error otherwise.


#6

I can’t do this on my local-host? I can’t use this trick for me development work then.


#7

Are you running a webserver on your local machine? If so, it will work. I just meant you can not just open the file locally like file:///C:/project/index.html


#8

Yes I am. Perfect then! thanks again @RandellDawson


#9

One more question, would this be consider a good practice or would you say it’s better to insert the code in the html files? I just think having a general controller like your example is better for maintainability.


#10

If you were using a server side language like php, you could use php include syntax and directly include the html of the files also. There is no reason to repeat html across multiple files, because if you need to make a change, you would have to manually change each of those sections in the files vs. making a single change which the code above will handle.


#11

That’s what I thought, thanks for your help.