user3187759 user3187759 - 4 months ago 57
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?


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:

   <script src=""></script>
   <div id="result">
      <%- include partials/content.ejs %>
   <button id="change">change</button>
    var $result = $('#result'); 
    $('#change').click(function() {

Then you need a controller on the backend like:

app.get('/content2', function (req, res) {