npm install cshtml
bash
npm install cshtml
`
$3
Simply set the view engine as 'cshtml' and call the response.render function. The first parameter is the name of the file (you don't need the .cshtml extension). The 2nd paramenter is the view model (see below) which is optional.
`js
var express = require('express');
var app = express();
app.set('view engine', 'cshtml');
app.get('/', function (req, res) {
var params = {title: "hello world"};
res.render('Index', params);
});
app.listen(3000, function () {
console.log('listening on port 3000');
});
`
$3
Chainsaw.js also easily integrated with Hapi.js. If you are unfamiliar with Hapi.js I advise you to review their tutorials. I am showing only the relevant parts because the code is long. Simply define the view engine:
`js
server.views({
engines: { html: require('cshtml') },
path: __dirname + '/views'
});
`
I chose in the above example to work with html files instead of cshtml. You can choose whatever file extension you wish. Then use the standard reply.view command. The first paramater is the name of the file. The second is your object view model.
`js
reply.view('index', {
title: 'welcome',
message: 'Index - Hello World!'
});
};
`
$3
First you need to 'require' the cshtml model. Then you use the render function with 3 parameters:
- the file to be rendered
- the view model (see below)
- callback function
The callback function receives two parameters: error (if any) and the result which is the rendered HTML.
`js
var http = require('http');
var cshtml = require('cshtml');
var params = {title: "hello world"};
http.createServer(function(request,response){
response.writeHead(200, {"Content-Type": "text/html"});
cshtml.render('views/Index.cshtml', params, function (err,res) {
if(err)
throw err;
response.end(res);
});
}).listen(8000);
`
$3
Just like most HTML rendering scripts you have an object with parameters that you want to sprinkle all over your HTML. Chainsaw.js supports all variables including arrays and functions.
`js
var viewModel = {title: "welcome",
people: [
{name: "bob" ,age:24},
{name: "larry",age:32}
],
printName: function(person){
return person.name + " : his age is "+person.age;
}
}
`
$3
If you're using Express.js, you have use the cshtml extension. If you're using Hapi.js, the file extension is defined in the view engine (see above). If not, you can call them whatever you want, for example:
- Index.html
- Index.txt
- Index.johnDoe
- etc.
$3
Simple double square brackets:
`html
[[title]]
`
Renders to…
`html
welcome
`
You can also use interpolation for more complex code (based on the view model above):
`html
[[people.length > 3 ? "long":"short"]]
[[ printName(people[0])]]
`
Renders to …
`html
short
bob : his age is 24
`
$3
`js
@foreach(var person in people)[[
[[person.name]] [[person.age]]
]]
`
Renders to…
`html
bob 24
larry 32
`
You can also loop over properties in an object.
In this example let's assume obj = { name: barney, age: 25 }
`html
@foreach(var prop in obj)[[
[[prop]] [[obj[prop]]]
]]
`
Renders to...
`html
name barney
age 25
`
$3
`js
@for(var i = 0; i < people.length; i++) [[
[[people[i].name]] [[people[i].age]]
]]
`
Renders to…
`html
bob 24
larry 32
`
$3
The if statement starts with a @if()... You can follow it with multiple else if's and of course an else. If's can also be nested within other @if block.
`js
@if(people[0].name == "harold") [[
the name is harold
]] else if( people.length == 3) [[
there are 3 people
]] else [[
the sky is blue
]]
`
Renders to…
`html
the sky is blue
`
$3
A switch case block starts with a @switch(). It's followed by cases. If the case is true, the HTML in the brackets is rendered. You can also add a case default.
`js
[[var temp = Math.floor(Math.random() * 5)]]
@switch(temp)
case 0:[[
you got zero!
]]
case 1:[[
you got only one
]]
case 2:[[
you got two
]]
case default: [[
you got [[temp]]
]]
`
$3
You can define variables using this format:
`js
[[var temp]]
`
or
`js
[[var temp = 12]]
`
If you want to declare a few variables, you'll need to declare them one at a time. Each one in its own brackets [[ ]].
$3
Any code you want to execute can be wrapped in a @[[ ]]. Brackets prefixed with the @ symbol will not render anything.
Important note: any variables declared in these code brackets @[[ ]] , cannot be accessed outside the code block. If you want to create a variable that is accessible outside the code block, use the [[var..]] syntax (see above).
Another important note: notice that the syntax within the code brackets is regular javascript, i.e. using if(){} and for(){}and not if()[[ ]] and for()[[ ]].
`js
[[var avg = 0;]]
@[[
for(var i = 0; i < people.length;i++){
avg += people[i].age;
}
avg = avg / people.length;
]]
The average age is [[Math.floor(avg)]]
`
Will render to
`html
The average age is 28
`
$3
A partial is a different file which contains more HTML that needs to be inserted into your main HTML page. All view model parameters are available in the partial. In your main file add this line:
`
@render [file path]
`
##### views/Index.cshtml
`js
@foreach(var person in people)[[
@render views/partials/text.cshtml
]]
`
##### views/partials/text.cshtml
`html
[[person.name]] [[person.age]]
`
Renders to…
`html
bob 24
larry 32
`
$3
Using layouts are useful when you want all the pages to have the same header and footer for example. On the main file being rendered you add on top the layout command:
`
@layout [path to layout file]
`
On the layout file, you have to add the @renderBody command to specify where the content is supposed to be rendered. You can also work with several layers of layouts:
##### views/Index.cshtml
`html
@layout views/innerLayout.cshtml
text text
`
##### innerLayout.cshtml
`html
@layout views/layout.html
@renderBody
`
##### Layout.cshtml
`html
[[title]]
@renderBody
`
Renders to...
`html
welcome
text text
`
$3
The 'chainsaw command symbol @' doesn't need escaping. If it's followed by a space or a command it doesn't recognize it just renders the @ as is.
Double square brackets have to be escaped using two preceding asterisk [[ and ]]:
`
[[title]]
`
Renders to…
`
[[title]]
`
$3
Section rendering comes to solve a common problem: You have a site with several content pages and a layout page for all them. Each content page has its own js and css files that need to be loaded in the tags that's on the layout file. How do you easily manage this? the answer - using sections.
On your layout page you designate where each section should be rendered.
##### layout.html
`html
CHainsaw.js
@renderSection scripts
@renderSection styles
`
In the above example, I created two sections named 'styles' and 'scripts'.
Now lets say I have two content pages: home.cshtml and about.cshtml. So on each page, I will reference the section and add within the square brackets [[ ]], what I want rendered in that section:
##### home.cshtml
`html
@section scripts[[]]
@section styles[[]]
`
##### about.cshtml
`html
@section scripts[[]]
@section styles[[]]
`
The section names in @section [name] has to correspond to an existing @renderSection [name].
The rendered home page will look like this:
`html
Chainsaw.js
`
We can also have several @section's with the same name on the same page and they will all be rendered together in the relevant section.
$3
If any command is wrapped in the usual HTML comment tags, it will be ignored.
`html
`
Renders as…
`html
``