The pug template engine in node.js getting started
When it comes to node.js template engines I am a big fan of ejs, but a pretty nice alternative is pug (formerly known as jade). It uses a clean whitespace sensitive syntax similar to markdown, but a bit more powerful. I still like ejs a lot because it is pretty much just like html but allows for embedded javaScript, put pug is kind of like markdown in the sense that it helps keep things neat, clean, and maybe more readable.
1 - pug js by itself or with a framework like express
If you are interested in learning more about the language itself there is a good guild for that at the official pug website. In this post I am going to be focusing on the use of the node.js npm package without any additional framework being used like express. However I have wrote a post in which I write more about using pug js with express.js
2 - pug js setup
As with most projects like this I set up a test folder, and install the package with npm.
|
|
One that is done I made a basic.js file that will be a hello world sort type js file that uses the project, that looks like this:
|
|
In this basic example I am using pugs render method that accepts a string of pug text, and returns plain old html.
|
|
3 - Some basics of the language
With pug the first few characters are interpreted as a tag, and a return is considered an end of the tag. Tags can also be nested by placing a return right after writing the first tag.
|
|
becomes
|
|
For a more compleate overview of the laguage it might be a good idea to check out the site on pug.
4 - Read *.pug files
Storing pug as an external file should have the *.pug extension, in addition reading pug files is a pretty straightforward process of just using the pug.readFile method.
I made a readfile.js file that I placed in the root of my test_pug project folder like this.
|
|
I also made a pugfiles folder in the project, and made some *.pug files to read. One of the files I made is called full.pug which looks like this:
|
|
So then I can call my readfile script from the command line and get the rendered html of a pug file just like this:
|
|
which will give me this html from full.pug
|
|
5 - Conclusion
There is a great deal more to pug such has how to handle partials, I might write a few more posts on pug if I get to it but I have a lot on my plate when it comes to what more to write about in the wonderful world of javaScript and node.js programing.