I'm a front-end developer. When I write a html
code I repeat my self a lot by copy and paste (header section, footer section, etc).
How I can write modularize my html
files? Like separate header.html
and footer.html
, and after that call both in index.html
... same as erb
in Ruby on rails
? (I don't like jade
lang)
In PHP we would do something like this:
index.php
<?php
include 'inc/head.inc.php'; //DOCTYPE and <head> stuff
include 'inc/header.inc.php'; //NAV or other top-of-page boilerplate
?>
<div id="uniqueDIV">
//Your unique page-specific divs can go here
</div>
<?php include 'inc/footer.inc.php'; ?>
So, in your head.inc.php
file, you just have the usual DOCTYPE and <head>
portion of your page file.
In Ruby, it appears the equivalent instruction is something like:
load "inc/head_inc.rb" -- OR --
require_relative "inc/head_inc.rb"
https://practicingruby.com/articles/ways-to-load-code
Another option is to use a bit of js/jQuery to populate parts of the document. If you don't have PHP, this is 2nd best option. It's less optimal than PHP because the js/jQ code will run after the page is fully rendered, which may cause a minuscule (but noticeable) lag before the code appears.
For example:
html
<div id="navbarDIV"></div>
js/jQuery:
<script type="text/javascript">
$(function(){
$('#navbarDIV').load( 'inc/navbar.inc.html' );
});
</script>
Note that you will need jQuery loaded to use the above code. Simple as this line in your <head>
:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
jsFiddle demo
Final note: the script tag can be included in your <head>
as an external file, or it can be plopped anywhere in your document with the rest of the html. Whatever works. But <head>
as external file, or last element in body (also as an external file) are preferred.
Final final note: the ".inc." naming convention is not required, it's just my own practice. Include file could be named head.html
or head.php
or etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With