IonicaBizau / ajs

:crystal_ball: Asynchronous templating in Node.js
MIT License
21 stars 6 forks source link

`<%= JSON.stringify(obj) %>` does not escape JSON output? #38

Open akirattii opened 3 years ago

akirattii commented 3 years ago

I recently started using ajs the greate alternative of ejs to improve blocking behavior of it. Well, I found that ajs seems not to escape <%= JSON.stringify(obj) %> in template.

Premise:

ajs example

server.js

const express = require('express');
const app = express();
const path = require('path');

// view engine setup
const ajs = require('ajs');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ajs');

app.get("/", function(req, res) {
  const data = {
    obj: { aaa: 123 },
  };
  res.render("index", data);
});

app.listen(3000);

views/index.ajs

<div><%= JSON.stringify(obj) %></div>

output:

<div>{"aaa":123}</div>

Oops, JSON output is not escaped!?

ejs example

In the case of ejs, it outputs escaped JSON looks like this:

output: (JSON output escaped)

<div>{&#34;aaa&#34;:123}</div>

views/index.ejs (contents is same as index.ajs)

<div><%= JSON.stringify(obj) %></div>

server.js (using ejs)

const express = require('express');
const app = express();
const path = require('path');

// view engine setup
const ejs = require('ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get("/", function(req, res) {
  const data = {
    obj: { aaa: 123 },
  };
  res.render("index", data);
});

app.listen(3000);

Is it a bug? Thank you in advance.

IonicaBizau commented 3 years ago

Not really a bug, but can be improved. Contributions are welcome in this direction.

Harm-Nullix commented 3 years ago

You should just use the <div><%- JSON.stringify(obj) %></div> instead of <div><%= JSON.stringify(obj) %></div> and you will get your json