public
Last active

Application bidon "forum" d'exemple

  • Download Gist
app.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/** Liste des threads du forum */
const threads = [
{ id: 1, title: 'First thread' },
{ id: 33, title: 'Oh noes, Jesus died' },
{ id: 42, title: 'Ze answer' }
]
 
/** Déclaration de l'application */
var app = require('express').createServer().configure(function() {
 
/** Les vues sont dans "./views" */
this.set('views', __dirname + '/views')
/** On utilise des templates EmbedJS */
this.set('view engine', 'ejs')
 
/** Ces variables seront toujours disponibles dans les vues,
ça évite de redéclarer des variables communes du layout par exemple */
this.set('view options', {
title: 'Forum'
})
 
/** Liste des threads sur "/" ou "/threads" */
function listThreads(req, res, next) {
res.render('index', { threads: threads })
}
this.get('/', listThreads)
this.get('/threads', listThreads)
 
/** Détail d'un thread sur "/thread/:id" */
function detailThread(req, res, next) {
var thread = threads.filter(function(t) { return t.id==req.params.id })[0]
if (!thread) {
res.send(404)
} else {
res.render('thread', { thread: thread })
}
}
this.get('/thread/:id', detailThread)
 
})
 
/** On démarre le serveur sur le port 8080 */
app.listen(8080)
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{
"author": "",
"name": "forum",
"description": "Application bidon, pour exemple de réutilisation",
"version": "0.0.1",
"repository": {
"url": ""
},
"engines": {
"node": "*"
},
"dependencies": {
"express": "*",
"ejs": "*"
},
"devDependencies": {},
"main": "app.js"
}
views:index.ejs
1 2 3 4 5 6 7
<h2>Threads</h2>
 
<ul>
<% for (var i=0, nbThreads=threads.length; i<nbThreads; ++i) { %>
<li><a href="/thread/<%= threads[i].id %>">Thread #<%= threads[i].id %>
<% } %>
</ul>
views:layout.ejs
1 2 3 4 5 6 7
<html>
<head><title><%= title %></title></head>
<body>
<h1>Forum - <%= title %></h1>
<%- body %>
</body>
</html>
views:thread.ejs
1 2 3 4 5
<h2><%= thread.title %></h2>
 
<p>Content of the thread...</p>
 
<p><a href="/threads">Back to index</a></p>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.