未加星标

Simple routing and unobtrusive template engine in Node JS

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

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!

Problem courtesy of: jonhobbs

Solution 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);

Solution courtesy of: Hector Correa

Discussion

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.

Discussion courtesy of: Jeremythuff

This recipe can be found in it's original form on Stack Over Flow .

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

tags: html,gt,lt,app,res,your
分页:12
转载请注明
本文标题:Simple routing and unobtrusive template engine in Node JS
本站链接:https://www.codesec.net/view/597095.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(25)