what can this ejs be look like in jade? - node.js

I am learning how to build simple CRUD web application and instruction is written in ejs. However, I just start learning jade and do not know how can I convert this ejs code to jade.
<% layout( 'layout' ) -%>
<h1 id="page-title"><%= title %></h1>
<div id="list">
<form action="/create" method="post" accept-charset="utf-8">
<div class="item-new">
<input class="input" type="text" name="content" />
</div>
</form>
<% todos.forEach( function ( todo ){ %>
<div class="item">
<a class="update-link" href="/edit/<%= todo._id %>" title="Update this todo item"><%= todo.content %></a>
<a class="del-btn" href="/destroy/<%= todo._id %>" title="Delete this todo item">Delete</a>
</div>
<% }); %>
</div>
and this is what I've done,
extends layout
h1#page-title= title
#list
form(action="/create" method="post" accept-charset='utf-8')
.item-new
input(type='text' name='content')

So you want to know how to write that second part in jade. Each is one of Jades primary methods for iteration. And your code could be written something like this:
each todo in todos
.item
a(class="update-link" href="/edit/"+todo._id title="Update this todo item")= todo.content
a(class="del-btn" href="/destroy/"+todo._id title="Delete this todo item") Delete
Here is a link for jades documentation about iterations: Jade Iterations.

Related

JSDOM not loading EJS pages in Node

I tried to load an EJS page using JSDOM however, I can't seem to load the page.
Here's part of my script in app.js:
const { JSDOM } = require("JSDOM");
const dom = new JSDOM('<!DOCTYPE html><p>Hello world</p>');
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
const list_dom = new JSDOM('views/list.ejs');
console.log(list_dom.window.document);
The first console log is just to make sure that I'm getting JSDOM to work.
Here's the result:
Hello world
Document { location: [Getter/Setter] }
I've tried variations of "views/list", and "views/list.ejs".
Here's my list.ejs:
<%- include('partials/header') -%>
<div class="box" id="heading">
<h1><%=listTitle%></h1>
</div>
<div class="box">
<% newListItems.forEach(function(item){ %>
<form action="/delete" method="post">
<div class="item" contenteditable="true">
<input type="checkbox" name="checkedItem" value="<%=item._id%>" onChange="this.form.submit()">
<p><%=item.name%></p>
</div>
<input type="hidden" name="listName" value="<%=listTitle%>"></input>
</form>
<% }); %>
<form class="item" action="/list" method="post">
<input type="text" name="newItem" placeholder="New Item" pattern="[a-zA-Z][a-zA-Z0-9\s]*" autocomplete="off" required autofocus>
<button type="submit" name="list" value=<%=listTitle%>>+</button>
</form>
</div>
<%- include('partials/footer') -%>

Why is my ejs outputting the actual html code and not rendering it as html?

I am doing some simple validation on a form and using bootstrap for alert dismissing. I have an ejs partial for displaying error messages. When trying to render the error message its just showing the actual block of code.
Here is my partials ejs:
<% if(typeof errors != 'undefined') { %>
<% errors.forEach(error => { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<%= error.msg %>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<% }) %>
<% } %>
Here is where I include that partial to the register.ejs file I have
<%= include ("./partials/messages") %>
<form action="/users/register" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input
type="name"
id="name"
name="name"
class="form-control"
placeholder="Enter Name"
value="<%= typeof name != 'undefined' ? name : '' %>"
/>
Here is a screenshot of what it is outputting:
Why is it showing the actual code instead of rendering as HTML?

Node.js - rendering a undefined variable

Maybe the name of the title is wrong but I have a specific problem. The thing I want to do is to show possibilities of editing and deleting a post if a user is an admin. I have a local variable called currentUser that holds data specifically username, password, and role. This line of code works fine if the user is logged in but the problem that I have is when there is no data in local variable. if i give a statement if(currentUser == undefined or null) i still get a error and the site is not rendering(error that i get is role is not defined). Since I'm still new to this I believe currentUser data is coming from a middleware function from passport js. My question is how to render a page when currentUser is undefined.
Thanks in advance!
<% menu.forEach(function(menu){ %>
<div class="col-lg-4 col-md-6 col-12 p-2 m-0 d-inline-block">
<div class="card" style="width: 22rem; ">
<img class="card-img-top img-fluid" src="<%= menu.pictureUrl %>" alt="Card image cap">
<div class="card-body">
<div style="height: 9rem;">
<h5 class="card-title"><%= menu.meal %></h5>
<div style="height: 4rem;">
<p class="card-text"><%= menu.description %></p>
</div>
<div style="height: 4rem;">
<p class="card-text"><strong><%=menu.price %>,00 Kn</strong></p>
</div>
</div>
<% if(currentUser.role == undefined){ %>
Stavi u košaricu
<%} else if(currentUser.role === "admin"){ %>
Uredi
<div class="d-inline">
<form class="d-inline" action="/menu/<%=menu._id%>?_method=DELETE" method="post"><button
class="btn btn-danger">Obriši</button></form>
</div>
<%}%>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</div>

How do I return the blogs in my database and render them by sorting them according to the most recent?

I have some blog posts in my Database (MongoDB) which I want to render to the screen by sorting them according to the most recent post. Please I need a solution or tutorial link to the solution. Thanks in advance
I have tried using the .toDateString() JavaScript inbuilt method which sometimes returns the most recent and sometimes doesn't for me.
<div id="top2">
<div class="row">
<% blogs.forEach((blog) => { %>
<div class="col-md-3 col-sm-6 thumb">
<img src="<%= blog.image %>" />
<div class="caption">
<h3><%= blog.title %></h3>
<p><%- blog.content.substring(0, 100) %>...</p>
<p id="created"><span id="author"><%= blog.author.username %></span> - <%= blog.created.toDateString() %></p>
</div>
<br>
<br>
</div>
<% }) %>
</div>
</div>
</div>
I expect the returned blogs from the database to be sorted by the date created.

Pass Data from MongoDB to Bootstrap Modal Using EJS

I'm building an express app which comprises ejs and bootstrap for rendering views, node and express for server side and mongodb for storage.
I have a form (contained in a modal) in which I can post data. After submitting the form, the values are saved to mongodb.
Here's the snippet for edit:
<td><%= cats.image %></td>
<td><a type="button" data-toggle="modal" data-target="#editCategory" href="#">Edit</a>
// without using the modal above, I'll have to create a new page to edit only one item
// I think it's a waste of page space and bad UX, so I am going with the modal
<!--<a href="/admin/categories/edit-category/<%= cats._id %>">--> // I want to get the values from this id and show in the modal
<!--<button type="button" class="btn btn-primary btn-sm">Edit</button>-->
<!--</a>-->
</td>
When I click on the edit button, I want to get the id of the item and retrieve it's values to display in the modal.
Here's the full modal view:
<!-- Edit Category Modal -->
<div class="modal fade" id="editCategory" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="/admin/categories/edit-cateory/<%= %>" method="post" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button>
<h4 class="modal-title" id="myEditCategoryLabel">Edit Category</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Title</label>
// this value should come from the category id but don't know how to pass it
<input value="<%= %>" name="title" class="form-control" type="text" placeholder="Category Title"> <br>
<label>Upload Image</label>
<input class="form-control selImg" type="file" accept="image/*" onchange="showImage.call(this)">
<img src="#" class="imgPreview" style="display: none; height: 100px; width: 100px">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save Edits</button>
</div>
</form>
</div>
</div>
</div>
How can I pass the data from mongodb to the modal using ejs?
Any help will be much appreciated.
Store your ID somewhere: hidden inputs or data-attributes.
<tr data-id="<%= cats.id %>">
<td><%= cats.image %></td>
<td>
<a type="button" class="edit" href="#">Edit</a>
</td>
</tr>
Then, create an onclick event handler such that, upon clicking on the button,
it will fetch the extra data via AJAX and open the modal dynamically after you get a response.
$('a.edit').click(function (e) {
e.preventDefault();
var tr = $(this).closest('tr'),
modal = $('#editCategory');
// make AJAX call passing the ID
$.getJSON('/admin/categories/get-cateory/' + tr.data('id'), function (data) {
// set values in modal
modal.find('form').attr('action', '/admin/categories/get-cateory/' + tr.data('id') );
modal.find('[name=title]').val( data.title );
// open modal
modal.modal('show');
});
});
You will need to create a route for fetching a single object (I'll leave that to you)
app.get('/admin/categories/get-cateory/:id', function (req, res) {
// TODO: fetch data using passed ID
// once you have the data, simply send the JSON back
res.json(data);
});

Resources