Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Render a non-specific amount of results with express/ejs

Render a non-specific amount of results with express/ejs

Problem

I'm trying to create a basic blog platform to help me get my feet wet with node. I'm using Express as a framework and ejs as my rendering engine. On my homepage, I'd like to display the last ten blogs. So far, I have:

"use strict";
var mongo = require("mongodb")
    , server = new mongo.Server("localhost", mongo.Connection.DEFAULT_PORT, {auto_reconnect: true, safe:true})
    , mdb = new mongo.Db("blog", server)
    , querystring = require("querystring")
    , express = require('express')
    , app = express();

app.configure(function() {
    app.set('view engine', 'ejs');
});

module.exports = {
    home: function home(req, res) {
        var blogs;
        //Load blogs from db
        mdb.open(function(err, db) {
            db.collection("blogs", function(err, collection) {
                var stream = collection.find({}, {"limit": 10, "sort": {"created": -1}}).stream();
                stream.on("data", function(item) {
                    app.render('blogItem', {title: item.title, content: item.content}, function(err, html) {
                        if(err) { console.error(err);   return; }
                        blogs += html;
                    });
                });
                //Render the finished page
                stream.on("end", function() {
                    res.render('home', {title: "AwesomeBlog", content: blogs});
                    db.close();
                });
            });
        });
    }
};

ejs files:

home.ejs



!

Admin section

blogItem.ejs

While this technically "works", the rendered Html per-blog is interpreted as plain text, resulting in

AwesomeBlog!

Hi

test 123

Awesome title

Awesome text

FIRST

POST!

Admin section

How can I fix this in this case?

What's the best practice for what I'm trying to do?

Problem courtesy of: SomeKittens

Solution

That's a safety feature built-into EJS. It stops your users from embedding html that contains javascript exploits (XSS) in your pages. (They can still submit unsafe strings in form requests, etc, but your template escapes it to prevent browser exploits.)

To turn it off (for HTML content you can trust):

Escapes html by default with 
Unescaped buffering with 

Simply switch the tags in your template like this:

Solution courtesy of: rdrey

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Render a non-specific amount of results with express/ejs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×