Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added extending-templates example. Closes #730

  • Loading branch information...
commit dbbe7be891768dae61686601c79c1aa3c2399a77 1 parent 09c9452
@tj tj authored
View
66 examples/extending-templates/app.js
@@ -0,0 +1,66 @@
+
+/**
+ * Module dependencies.
+ */
+
+var express = require('../../lib/express');
+
+var app = express.createServer();
+
+// Register ejs as .html
+
+app.register('.html', require('ejs'));
+
+// Optional since express defaults to CWD/views
+
+app.set('views', __dirname + '/views');
+app.set('view engine', 'html');
+
+// Dummy users
+var users = [
+ { name: 'tj', email: 'tj@sencha.com' }
+ , { name: 'ciaran', email: 'ciaranj@gmail.com' }
+ , { name: 'aaron', email: 'aaron.heckmann+github@gmail.com' }
+];
+
+// dynamic helpers are simply functions that are invoked
+// per request (once), passed both the request and response
+// objects. These can be used for request-specific
+// details within a view, such telling the layout which
+// scripts to include.
+app.dynamicHelpers({
+ // by simply returning an object here
+ // we can set it's properties such as "page.title"
+ // within a view, and it remains specific to that request,
+ // so it would be valid to do:
+ // page.title = user.name + "'s account"
+ page: function() {
+ return {};
+ },
+
+ // the scripts array here is assigned once,
+ // so by returning a closure, we can use script(path)
+ // in a template, instead of something like
+ // scripts.push(path).
+ script: function(req){
+ req._scripts = [];
+ return function(path){
+ req._scripts.push(path);
+ }
+ },
+
+ // to expose our scripts array for iteration within
+ // our views (typically the layout), we simply return it
+ // here, and since composite types are mutable, it will
+ // contain all of the paths pushed with the helper above.
+ scripts: function(req){
+ return req._scripts;
+ }
+});
+
+app.get('/', function(req, res){
+ res.render('users', { users: users });
+});
+
+app.listen(3000);
+console.log('Express app started on port 3000');
View
11 examples/extending-templates/views/layout.html
@@ -0,0 +1,11 @@
+<html>
+ <head>
+ <title><%- page.title %></title>
+ <% for (var i in scripts) { %>
+ <script src="<%= scripts[i] %>"></script>
+ <% } %>
+ </head>
+ <body>
+ <%- body %>
+ </body>
+</html>
View
8 examples/extending-templates/views/users/index.html
@@ -0,0 +1,8 @@
+<% page.title = 'Users' %>
+<% script('/javascripts/jquery.js') %>
+<% script('/javascripts/users.js') %>
+
+<h1>Users</h1>
+<ul id="users">
+ <%- partial('user', users) %>
+</ul>
View
1  examples/extending-templates/views/users/user.html
@@ -0,0 +1 @@
+<li><%= user.name %> &lt;<%= user.email %>&gt;</li>
Please sign in to comment.
Something went wrong with that request. Please try again.