How to use the renderFile function from swig

Find comprehensive JavaScript swig.renderFile code examples handpicked from public code repositorys.

swig.renderFile compiles a Swig template file with data to generate HTML output.

166
167
168
169
170
171
172
173
174
175
    varControls: ['{=', '=}'] //Angular uses the same set ( {{ and }} ), and we don't want swig interpreting angular syntax.
});

var indexPromise = Q.defer();
fileWritePromises.push(indexPromise.promise);
swig.renderFile(path.resolve(__dirname, '../../', './resources/index.html'), structure, function (err, output) {
    if (err) {
        console.log(err)
        indexPromise.reject(err);
    }
fork icon35
star icon165
watch icon12

3759
3760
3761
3762
3763
3764
3765
3766
3767
3768

/**
 * Compile and render a template file for final output. This is most useful for libraries like Express.js.
 *
 * @example
 * swig.renderFile('./template.html', {}, function (err, output) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log(output);
fork icon0
star icon1
watch icon0

+ 3 other calls in file

How does swig.renderFile work?

swig.renderFile is a function in the Swig templating engine that takes a template file path and a data object, then compiles and renders the template using the data, returning the resulting string.

329
330
331
332
333
334
335
336
337
338
  swig.renderFile(templateIndex, model);
  // return;
}
var renderedTemplate;
if (req.query.env === 'dev') {
  renderedTemplate = swig.renderFile('index.html', model);
  renderedTemplate = renderedTemplate.replace(/="\/assets\//g, '="/dev/assets/')
  // res.send(renderedTemplate.replace(/="\/assets\//g, '="/dev/assets/'));
} else {
  renderedTemplate = swig.renderFile('index.html', model);
fork icon0
star icon0
watch icon1

+ 5 other calls in file

117
118
119
120
121
122
123
124
125
126
        };
        tplVars.bundle = global.bundle;

        grunt.log.writeln('Writing HTML to ' + htmlFile);

        grunt.file.write(htmlFile, swig.renderFile(file, grunt.util._.extend(globalVars, tplVars, contextVars)));
    }
});

async();
fork icon0
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
const swig = require("swig");
const data = { name: "John", age: 30 };
swig.renderFile("views/index.html", data, function (err, output) {
  if (err) {
    console.error(err);
  } else {
    console.log(output);
  }
});

In this example, we first import the swig module. We define an object data with some properties. We then call swig.renderFile, passing the path to a template file, the data object, and a callback function. The callback function is called once the rendering is complete, and if there is an error, we log it to the console. Otherwise, we log the rendered output to the console.