Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

raz

Package Overview
Dependencies
Maintainers
1
Versions
96
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

raz

Razor-like syntax for templating views in Express framework by mixing HTML with JavaScript.

  • 0.0.8
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16
decreased by-38.46%
Maintainers
1
Weekly downloads
 
Created
Source

Razor-Express View Template Engine

(draft)

When I just started to dive into the world of Node.js after years of working with ASP.NET MVC I couldn't find any view template engine that was as convenient, elegant, concise, and syntactically close to native HTML markup language as Razor was. To be more precise, ASP.NET MVC Razor markup is a hybrid of HTML markup and C# programming language. And when it comes to code it's also syntactically close to the original C# language. So, this is exactly what I expected to see in the NodeJS world (except that it should be JavaScript instead of C#).

The closest to Razor currently supported library I could find was Vash, but in some points, it was quite different from ASP.NET MVC Razor syntax which I was used to and it just looked much less concise and convenient to me (the concepts of layouts and partial blocks, for example). I may be exaggerating the merits of ASP.NET MVC Razor and maybe it's all just a matter of habit, but whatever it is I decided to create something more similar for using it with ExpressJS library.

Although I tried to make my library as close as possible to Razor there are certain differences that need to be taken into account. So, enough lyrics, let's get started and look into my creation... it's my first JavaScript creation actually.

Quick Start

Assuming that you are already familiar with the basic idea let's look at a simple example.

Our first component is a model:

{
    title: "Names of the Days of the Week",
    days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};

which is just a JavaScript object. And we want to get some HTML displaying the data of this model in some simple way. Later we might want to change the model data and still get the same HTML structure to display it. So, we need our second component which is called view-template:

<h3>@Model.title</h3>
<ul>
@for(var i = 0; i < Model.days.length; i++){
    var day = Model.days[i];
    <li>@day</li>
}
</ul>

As you can see the view-template (or just view) is nothing more than HTML markup mixed with JavaScript syntax. This is exactly what Razor-Express syntax is [!].

Now we are going to take these two components and "compile" them into pure HTML.

Node.js example

First, we'll be doing this "compilation" without creating any web-server to keep things as simple as possible. It can be done either in Node.js environment or in just the browser JavaScript. To do this we will declare two variables model and template:

const model = {
    title: "Names of the Days of the Week",
    days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};

const template = `
<h3>@Model.title</h3>
<ul>
@for(var i = 0; i < Model.days.length; i++){
    var day = Model.days[i];
    <li>@day</li>
}
</ul>`;

...which are pretty much self-explained as we remember what our two components are. Next, we have to compile them together using Razor-Express library to get the expected HTML.

// This code is meant for Node.js 
const razor = require("raz");
var html = razor.compileSync({ model, template });

Now let's display it in the console to make sure our expectations are fully met.

console.log(html);

Here's what we can see in the console:

<h3>Names of the Days of the Week</h3>
<ul>
    <li>Sunday</li>
    <li>Monday</li>
    <li>Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li>
</ul>

That's all! Isn't it simple?

If you'd like to see all these parts working together here is the playground of it.

Express web-server example

server.js file with comments:

// Create Express web server app.
const app = require('express')();

// Register 'Razor' template engine and the default extesnion for the view-template files.
// 'Express' will automatically find the Razor module (within the `node-modules` folder) using this extension. 
// If you decide to skip registering the engine then you will have to explicitly specify the file extension in the route handler.
app.set('view engine', "raz");

// Create the route for the "Index.raz" view-template.
// Note that we do not specify the file extension explicitly in this route because we already did it when registering the engine.
app.get('/', (req, res) => {
    const model = {
        title: "Names of the Days of the Week",
        days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    };
    res.render("./index", model);
});

// Express-app default port number.
const port = process.env.PORT || 8080;

// Starting Express-app.
const server = app.listen(port, () => {
    console.log("Server is up on port " + port);
});

// Catch Express-app errors.
server.on('error', function (e) {
    if (e.code === 'EADDRINUSE') {
        console.error('Address is in use, stopped.');
    }
});

index.raz file is just a view-template which is pretty much the same as in the previous example except we have to add some basic HTML markup. We put this file into the "views" folder which is a default folder for the Express app. Notice that the file has '.raz' extension which every Razor view file must have.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>@Model.title</title>
  </head>
  <body>
    <h2>@Model.title</h2>
    <ul>
    @for(var i = 0; i < Model.days.length; i++){
        var day = Model.days[i];
        <li>@day</li>
    }
    </ul>
  </body>
</html>

Now you if run node server.js command in console/terminal and open http://localhost:8080/ URL in your browser you will see the HTML page showing something like this:


Names of the Days of the Week

  • Sunday
  • Monday
  • Tuesday
  • Wednesday
  • Thursday
  • Friday
  • Saturday

:sparkles: The Express server app with Razor template engine works! :sparkles:

The source code of this example is available in RazorExpressExample repository.

Keywords

FAQs

Package last updated on 23 Nov 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc