I am working on a blogging application with Express, EJS and MongoDB.
In my posts.js
controller I have:
exports.getSinglePost = (req, res) => {
let id = req.params.id;
Post.findById(id, function(err, post){
if(err){
console.log('Error: ', err);
} else {
res.render('singlepost', {
website_name: 'MEAN Blog',
post: post
});
}
});
};
The singlepost.ejs view has the code:
<header class="masthead" style="background-image: url('assets/images/home-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1><%= post.title %></h1>
<span class="subheading"><%= post.short_description %></span>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<%= post.full_text %>
</div>
</div>
</div>
It works fine as long as the entry in the posts collection does not contain HTML tags:
{ "_id" : ObjectId("5e3063dbfa749d9229bab26f"), "title" : "Post One", "short_description" : "Lorem ipsum dolor sit amet.", "full_text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."}
But when it does contain HTML tags:
{ "_id" : ObjectId("5e317594fa749d9229bab271"), "title" : "Post One", "short_description" : "Dolor sit amet.", "full_text" : "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>"}
the singlepost
view renders HTML in the browser:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
In AngularJS the problem would be easely solved with ng-bind-html
, but I'm not using AngularJS in this project.
So, how can I fix this bug in EJS?
I have solved the problem by replacing <%= post.full_text %>
with <%- post.full_text %>
(=
with -
).
The singlepost
view now is like so:
<header class="masthead" style="background-image: url('assets/images/home-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1><%= post.title %></h1>
<span class="subheading"><%= post.short_description %></span>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<%- post.full_text %>
</div>
</div>
</div>