How to insert Jade markup into a DOM element in the browser

I am trying to design a webpage where a button click will add some buttons to a div. If I used raw html then with the help of jquery I would have used the following code segment to have my work done.

$('#div-id').html('')

But I am using Jade as template engine. So I need to insert Jade block dynamically for that the button click. I couldn't find any such example on the web. Can I do it? If yes, then how?

You can use Ajax to retrieve the compiled html from server:

$.get("/path/to/partial_view/").done(function(response) {
  $("#div-id").html(response.data);
});

/path/to/partial_view should be a view of your jade and return html compiled by engine

The solution depends on if you'd rather compile Jade in the browser or on the server. Documentation.

Client-side - Demo

include jade

<script src="//cdnjs.cloudflare.com/ajax/libs/jade/1.3.1/jade.min.js"></script>

compiling example

$.get('foo.jade').then(function(doc) {
  var html = jade.compile(doc)();
  $(myElem).append(html);
});

Server-side

Setup a route on the server to compile jade as usual and serve it.

// setup route
app.get('/templates/foo', function(req, res) {
  // render foo.jade as html
  res.render('foo');
}); 

Then, use ajax from the browser to retrieve the compiled template:

$.get('/templates/foo').then(function(html) {
  $(myElem).append(html);
});