问题
I'm currently trying to develop a site using node.js. I'm having some trouble due to my unfamiliarity with html and node.js. Is there any mechanism in either node.js or html where I don't have to recreate a header & footer for every single web page (eg: copy paste the html code each time)?
回答1:
Not sure this will answer you question but it's one way to add header and footer in HTML pages without repeating the code.
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
and in your main index.html file will be
<div id="header"></div>
<div id="content">
Main Content
</div>
<div id="footer"></div>
So the complete index.html will be look like this
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<div id="content">
Main Content
</div>
<div id="footer"></div>
</body>
</html>
回答2:
Since you said you are unfamiliar with html and nodejs i assume u are a beginner.
To achieve what you are looking for can be done in multiple ways and one of the ways is given by shehary which renders the page on client side(user's browser) and uses jquery to manipulate DOM to insert the header and footer. other ways include inserting the header and footer on server side using templates. some of the popular templates used in nodejs are ejs jade swig etc. you can also do it client side using jQuery , angularJS ,backboneJS etc. each of them have a their own positive and negative points.
来源:https://stackoverflow.com/questions/31486636/do-i-have-to-rewrite-an-html-header-everytime-i-want-to-use-it