Node.js
Express.js
ECT

Node.js+Express.js+ECT:routerからviewへobjectを渡す

More than 1 year has passed since last update.


バージョン

$ node -v

v6.2.1

$ cat package.json

{
≈≈≈
"dependencies": {
"ect": "^0.5.9",
"express": "~4.13.1",
≈≈≈
},
≈≈≈
}


cat routes/test.js

var express = require('express');

var router = express.Router();

/* GET calendar page */
router.get('/', function(req, res, next) {
res.render('test', {
str: "文字列",
obj: { "title": "hello", "money": 999 }
});
});

module.exports = router;


cat views/test.ect

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title>テストしてみる</title>
<script>
<!-- propertyがstringの場合、有無チェックは"if @str?.length :"で行う -->
<% if @str?.length : %>
console.log("str=<%= @str %>");
<% else : %>
console.log("no str");
<% end %>

<!-- propertyがobjectの場合、有無チェックは"if @obj :"で行う -->
<% if @obj : %>
var obj = <%- JSON.stringify(@obj) %>;
console.log("obj=" + JSON.stringify(obj));
<% else : %>
console.log("no obj");
<% end %>
</script>
</head>
<body>
</body>
</html>