This is a multi part question and I'm a complete newbie to Node so please be gentle:)

I have a very simple Node/express app set up returning an index.html without using routing...

var app = express();
var port = process.env.PORT || 1337;


app.use('/i', express.static(__dirname + '/i'));
app.use('/Stylesheets', express.static(__dirname + '/Stylesheets'));
app.use(express.static(__dirname));


app.listen(port);
console.log('listening on port ' +  port);

The index.html is served as a static file.

My next job is to start returning a few pages with proper routing, I've got as far as working out I need to put my routes in a routes.js file and "require" that file in my server.js file but I can't get my head around setting the routes up and every example/demo I see online seems to do it a different way. Any definitive examples of how to do this would really be appreciated.

The next part of the problem is that I want to include dynamic pages but don't know where to go with templating engines. I would like to use something "unobtrusive" so that my original HTML files still make sense when viewed in a browser.

On the front-end I would simply inject HTML into the page by first using a selector and then using the .html() method to alter the html, I could bind JSON data with a template and then inject it into the right place by looking for a classname etc. THis would be totally unobtrusive and wouldn't require any ugly {} brackets, inline javascript or directives. Psuedo code...

var data  = {"name":"John"};
var result = templateEngine.bind("/template.html", data)


$('.person').html(result);

That way, I could keep my original HTML clean and viewable, like this...

<div class="person">
    My Name is FirstName
</div>

The closest thing I can find is PURE - http://beebole.com/pure - but I'm not sure how to get it working with NODE (or even if it's compatible).

To add more complexity, whatever templating engine I use needs to be able to use sub-templates(partials?) so that I can include a header/footer etc which is te same on every page. I assume this can be done recursively by referencing sub-templates from within each main template where needed?

If you're still reading this then clearly you'll have worked out that I'm floundering here with a new technology and any help would be really appreciated!

有帮助吗?

解决方案

but I can't get my head around setting the routes up and every example/demo I see online seems to do it a different way. Any definitive examples of how to do this would really be appreciated.

Not sure what you have seen different in the examples, but the general pattern is like this:

app.**[HTTP VERB]**(**[URL]**, function(req, res){
    res.end('<html>hello world</html>');
});

The following code will accept all HTTP GET requests to the root URL of your site:

app.get('/', function(req, res){
    res.end('<html>hello world</html>');
});

While the following code will accept all HTTP GET request to /test in your site

app.get('/test', function(req, res){
    res.end('<html>hello world from the test folder</html>');
});

It's common to have a separate route for HTTP POST requests (e.g. when the user submits data back to the server). In this case the HTTP verb is POST as in the following example.

app.post('/test', function(req, res){
    res.end('<html>Thanks for submitting your info</html>');
});

In this case I am embedding the code to handle the request directly rather than referencing an external routes.js as you indicated just to make the examples cleaner in this question. In a real application you'll do it by referencing an external function so that your app.js stays lean and clean.

app.get('/test', routes.NameOfFunctionToHandleGetForSlashTest);
app.post('/test', routes.NameOfFunctionToHandlePostForSlashTest);

其他提示

I know this is an old question, but I have explored this topic recently, and came up with the following solution:

my original question

I have placed the following configuration on ejs:

 var ejs = require('ejs');

 server.configure(function(){
    server.set("view options", {layout: false});  
    server.engine('html', require('ejs').renderFile); 
    server.use(server.router);
    server.set('view engine', 'html');
    server.set('views', __dirname + "/www");
 });

This sets your view engine as ejs, your view directory as your static public html directory and tells ejs to process .html files as opposed to .ejs.

The routes can be handles like this:

 server.all("*", function(req, res, next) {
      var request = req.params[0];

          if((request.substr(0, 1) === "/")&&(request.substr(request.length - 4) === "html")) {
          request = request.substr(1);
          res.render(request);
      } else {
          next();
      }

  });

 server.use(express.static(__dirname + '/www'));

This routes all html requests through the view engine, and passes all other requests on down the stack to be sent as static files.

Your html can now look something like:

  <%include head.html%>
  <%include header.html%>

  <p class="well">Hello world!</p>

  <%include footer.html%>

you can have nested includes, and pass variables down into your includes. So for instance your include head can call:

 <title> <%= title %> </title>

and at the top of your index page you can include an object like:

 {var title: "Home"}

Anyway, maybe this will help out someone who is looking for a ultra easy way to handle includes while sticking with normal html.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top