---
title: "NodeJS Marko Quick Reference"
author: "fairy_xzc"
date: "2017-01-20T13:44:42Z"
tags: []
categories: ["Web前端"]
slug: "nodejs-marko-quick-reference"
draft: false
lastmod: "2017-01-20T14:04:20Z"
id: 2354215
url: "https://agilestyle.iteye.com/blog/2354215"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2354215](/blog/2354215)**

 

## Prerequisite

```
npm init
npm install express --save --registry=https://registry.npm.taobao.org
npm install marko --save --registry=https://registry.npm.taobao.org
```

 

## Project Directory

![](http://dl2.iteye.com/upload/attachment/0122/7206/1290d356-bb3d-3d28-be65-1b668da567e3.png)

 

## SRC

package.json

```
{
  "name": "hello-marko",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.0",
    "marko": "^3.14.0"
  }
}
```

 

server.js

```
require('marko/node-require').install();

var express = require('express');
var app = express();

app.get('/', require('./src/pages/home'));

app.listen(3000, function() {
	console.log('listening on port 3000');
});
```

   
template.marko

```
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Marko Demo</title>
</head>
<body>
	<h1>Marko Demo</h1>

	Hello ${data.name}
</body>
</html>
```

 

index.js

```
var template = require('./template.marko');

module.exports = function(req, res) {
	template.render({
		name: 'Marko'
	}, res);
};
```

Note:

index.js就相当于页面的controller 

 

## Run

![](http://dl2.iteye.com/upload/attachment/0122/7208/fd8e4626-e3b9-3666-8704-5f79f5b72817.png)  
Note：

启动node server之后，会自动生成一个template.marko.js文件，有兴趣的话，可以点开看看 

![](http://dl2.iteye.com/upload/attachment/0122/7220/640c5c7b-0ba0-3965-9c7f-b79780c7abd5.png)  
 

## Test

http://localhost:3000/

![](http://dl2.iteye.com/upload/attachment/0122/7222/da39dd4d-e910-392b-ab84-3a918bd09fdd.png)  
 

接着修改template.marko如下：

```
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Marko Demo</title>
</head>
<body>
	<h1>Marko Demo</h1>

	Hello ${data.name}

	<ul if(data.colors)>
        <li for(color in data.colors)>
            ${color}
        </li>
    </ul>
    <div else>
        No colors!
    </div>
</body>
</html>
```

修改index.js如下：

```
var template = require('./template.marko');

module.exports = function(req, res) {
	template.render({
		name: 'Marko',
		colors: ['red', 'green', 'blue']
	}, res);
};
```

重新run和test

![](http://dl2.iteye.com/upload/attachment/0122/7237/7d92943e-3a43-3a06-8920-7cfcd87ac881.png)

 

## Reference

[http://markojs.com/docs/marko/get-started/](http://markojs.com/docs/marko/get-started/)

[https://www.npmjs.com/package/marko](https://www.npmjs.com/package/marko)