问题
I am implementing server side rendering pages, For server side rendering I am using HTML, Node.js HandleBars. So From client side I am sending static HTML, JSON DATA. Handlebar will bind data with static page(In Node side). And in response I am getting HTML page with data.
Structure Of Code Below:
module.exports.renderTemplate = function (templateData, htmlSource) {
// I am getting dynamicElement JSON
// generate HTML dynamic element?
// How to add with final HTML.
template = Handlebars.compile(htmlSource);
html = template(templateData);
return(html)
}
Above code giving me final HTML, Below I am attaching console.log code.
htmlSource
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{staticElement.title}}</title>
<link rel="stylesheet" href="../../_global/xlib/bootstrap/css/bootstrap.min.css">
</head>
<body>
<header>
<div>
<a href="javascript:;" class="hamburger-icon"></a>
<h2 class="page-title">{{staticElement.title}}</h2>
</div>
</header>
<main>
<section class="card-container container-component">
<div class="card">
<h2>{{staticElement.text1}}</h2>
</div>
<div class="card">
<i class="icons import-enrollment-icon"></i>
<h2>{{staticElement.text2}}</h2>
</div>
</section>
</main>
<script src="../../_global/xlib/jquery/jquery.min.js"></script>
<script src="../../../scripts/utils.js"></script>
<script src="../../_global/scripts/utils.js"></script>
<script src="home.js"></script>
</body>
</html>
templateData
{ staticElement:
{ title: 'JHON',
text1: 'Ameo',
text2: 'Start'
},
{dynamicElement:
{"myBooks": [{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming"
}
]
}
}
Final HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{staticElement.title}}</title>
<link rel="stylesheet" href="../../_global/xlib/bootstrap/css/bootstrap.min.css">
</head>
<body>
<header>
<div>
<a href="javascript:;" class="hamburger-icon"></a>
<h2 class="page-title">JHON</h2>
</div>
</header>
<main>
<section class="card-container container-component">
<div class="card">
<h2>Ameo</h2>
</div>
<div class="card">
<h2>Start</h2>
</div>
</section>
</main>
<script src="../../_global/xlib/jquery/jquery.min.js"></script>
<script src="../../../scripts/utils.js"></script>
<script src="../../_global/scripts/utils.js"></script>
<script src="home.js"></script>
</body>
</html>
When I want to create document.write. Then it is not working. because document.write will work with browser. I want to add dynamicElement JSON Data into the final HTML Without hard coding html tags, Means in future 5 or 10 json value will come in dynamicElement then no need to write html tag.
I am new in the handleBar and node side rendering. Thanks in advance.
来源:https://stackoverflow.com/questions/57234830/how-to-generate-dynamic-html-based-on-json