Question3r
Question3r

Reputation: 3742

separate Handlebars HTML into multiple files / sections

I want to create a page with only one route but I want to split the HTML code into multiple files.

When rendering this route I want the rendered file get the content from all template files and combine it to one page.

For example this template should render the following files:

I just want to keep the code separated because then I can build up a clean structure. Is that possible? Currently I am just able to render one file

router.get('/', (req, res) => {
    res.render('myTemplate');
});

I don't need to use Handlebars if there is a way with default HTML logic because I will only have one template for my page.

Upvotes: 1

Views: 1679

Answers (1)

Rohan Lekhwani
Rohan Lekhwani

Reputation: 500

Suppose you wish to render one file which is your main file and include header and footer files in it. Lets call your main file main.hbs and the header and footer html files as header.html and footer.html

Your route code would look like the following:

    router.get('/', (req, res) => {
    res.render('main');
});

header.html

<h1> Hi I'm the Header </h1>

footer.html

<h1> Hi I'm the Footer </h1>

You can include the header and footer templates in your main by using jQuery

main.hbs

<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script> 
$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>

Similarly you can include the Intro,Service,About,Contact,Imprint files in your main file by specifying their id's.

Upvotes: 2

Related Questions