Search code examples
javascriptnode.jsapiexpresspug

How to include jade template with each iteration in a loop?


I'm trying to include the same jade template with each iteration in a loop, so that if a user clicks on a button, it offers the same template no matter which iteration. This is for a blogging engine I'm creating. There is a deletePostModal.jade template I want to include for each post, and when the button is clicked on a particular post, the modal appears with the option to delete that post. The modal only appears when the button is clicked on the first post! Here is my blog.jade code:

      each post in postsList
        div#post-container(class='container-fluid')
          .row
            .col-md-6
              a(href='/blog/posts/#{post._id}')  
                h2 #{post.title}
                h4 Date and Time posting
                img#post-img(src=urlList[i])
            .col-md-1.offset-md-5
              if isAdmin
                include ./includes/deletePostModal.jade // Template I'm trying to include                   
                button.xxx#deletePostBtn X // Button to add template
          .row
            .col-md-12
              div#content-text-container
                p(id='content-text') 
                  | #{post.content}
          - i++

My deletePostModal.jade code:

#deletePostModal.modal
  // Modal content
  .modal-content
    .modal-header
      span.closeDeletePost ×
      h2 Modal Header
    .modal-body
      p Are you sure you want to delete post?
    .modal-footer
      a(href="api/blog/posts/#{post._id}/delete")
        button Yes
      button.closeDeletePost No

And my deletePostModal.js code:

// Get the modal
var deletePostModal = document.getElementById('deletePostModal');

// Get the button that opens the modal
var deletePostBtn = document.getElementById("deletePostBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("closeDeletePost")[0];

// When the user clicks the button, open the modal
deletePostBtn.onclick = function() {
      deletePostModal.style.display = "block";
};

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
      deletePostModal.style.display = "none";
};

This is the last step I need to complete my blog, and I've been banging my head for hours. Help is appreciated!


Solution

  • I'm guessing it's because you have multiple buttons with the same id.

    Created in button.xxx#deletePostBtn when you loop through posts.

    Then when you get the element by ID

    // Get the button that opens the modal var deletePostBtn = document.getElementById("deletePostBtn");

    It only works for the first post because that's the one it grabs.

    Try adding a unique ID to each button. Use the post ID or something like that.