cathy.sasaki
cathy.sasaki

Reputation: 4025

Rendering a file with swig templates without using express

I use swig (django style templating engine) with express successfully all the time. I'm trying to use swig outside of request/render and simply pass context to a swig marked up file and have it generate the HTML.

I can't figure out the API without using express.

From the website they have this example that I can't get to work: https://github.com/paularmstrong/swig/tree/bd3f5a0dc08078ffd4372fa61248f8d50d8cbbf8

var template  = require('swig'); // v1.1.0
var tmpl = template.compileFile('/path/to/template.html');
tmpl.render({
    pagename: 'awesome people',
    authors: ['Paul', 'Jim', 'Jane']
});

There is an error saying render doesn't exist on the tmpl object? (The compileFile seems to be working fine.)

There is clearly something I'm not understanding or that I need to include outside of the example.

update: Added in version number of swig after comments to make it clear what version I'm working with.

Upvotes: 1

Views: 4075

Answers (4)

Maneesh Singh
Maneesh Singh

Reputation: 575

Here is some steps to render swig template . 1. install swig using command npm install swig --save

-create server.js

var http = require('http'), swig=require('swig');
http.createServer(function(request, response){
var tpl = swig.compileFile('index.html');
renderedHtml =  tpl({
                         say:'hello word'
                    });
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(renderedHtml);
}).listen(8080);

-create index.html template file as.

    <html>
    <head>
    <meta charset="utf-8" />
   </head>
    <body>
     <h2>{{say}}</h2>   
    </body>
    </html>

Upvotes: 2

jonschlinkert
jonschlinkert

Reputation: 11007

Have you looked at https://github.com/assemble/assemble? Assemble is a static site generator based on Grunt, it's really easy to use, and Swig is one of the engines for Assemble. Here are some resources:

Upvotes: 2

Paul Armstrong
Paul Armstrong

Reputation: 7156

From comments on original question:

It looks like you're trying to use Swig@~1.0, yet the link you gave points to [email protected]. The API for Swig changed dramatically between v0 and v1.

Documentation for the current supported version can always be found at http://paularmstrong.github.io/swig/

Upvotes: 2

Kim T
Kim T

Reputation: 6426

Do you need to tell swig the path to the templates?

var swig  = require('swig');
swig.init({ root: __dirname + '/templates' });

var tmpl = swig.compileFile('home.html');
tmpl.render({
    pagename: 'awesome people',
    authors: ['Paul', 'Jim', 'Jane']
});

Upvotes: 0

Related Questions