I'm trying to create a dynamically included in an ejs page (using
<%- include('partials/content') %>
Let's assume your partials/content
file includes content like:
<h1>Lorem ipsum dolor sit amet</h1>
A file named partials/content2
:
<h1>consectetur adipiscing elit<h1>
Your main template file would wrap the partials content by a <div>
with the id result
and include a script file where you select this <div>
by using var $result = $('#result');
so you have it in a variable. Then you can register a click handler on your button. On click you request the wished template file and replace the content.
Main template:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="result">
<%- include partials/content.ejs %>
</div>
<button id="change">change</button>
<script>
var $result = $('#result');
$('#change').click(function() {
$result.load('/content2');
});
</script>
</body>
</html>
Then you need a controller on the backend like:
app.get('/content2', function (req, res) {
res.render('partials/content2');
});