user3187759 user3187759 - 2 months ago 42
Node.js Question

ejs include on click

I'm trying to create a dynamically included in an ejs page (using

<%- include('partials/content') %>
) on my node.js project.
Is there a way I can create a variable for the to-be-included page and change it on a button click?

Answer

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');
});